现在我对ReactiveSwift感兴趣并尝试将其添加到项目的网络操作中。但是使用observeResult方法有关于动作返回类型的一些问题。
查看模型:
final class TestViewModel: ViewModel {
var getListAction: Action<Void, Void, APIError>!
var arr = NSMutableArray()
override init() {
super.init()
self.getListBuild()
}
func getListBuild() {
getListAction = Action<Void, Void, APIError> { _ in
let signalProducer = SignalProducer<Void, APIError> { observer, disposable in
self.getList(observer)
}
return signalProducer
}
getListAction.apply().start()
}
func getList(_ observer: Observer<Void, APIError>) {
Network<UserDetailInfo>().requestList(router: RegistrationRouter(endpoint:.Login())).take(during: lifetime).startWithResult { (result) in
switch result {
case let .success(value):
self.arr = value as! NSMutableArray
print("success")
observer.sendCompleted()
case let .failure(error):
print("abort: \(String(describing: error.message))")
observer.send(error: error)
}
}
}
}
从控制器我试图像这样管理它:
final class ViewController: View {
var viewModel: TestViewModel?
func bindViewModel() {
self.viewModel = TestViewModel()
self.viewModel?.getListAction.events.take(during: lifetime).observeResult { (result) in
switch result {
case .success(_):
print("success")
print(self.viewModel?.arr.count as Any)
break
case let .failure(error):
print(error.localizedDescription);
break
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.bindViewModel()
}
}
尽管viewModel中的getList方法返回失败,但情况如下:
方法返回成功,但事实并非如此。应该是失败。请让我了解这个主题的问题。
答案 0 :(得分:2)
您观察到的event
流永远不会返回失败。请参阅其文档:
/// A signal of all events generated from applications of the Action.
///
/// In other words, this will send every `Event` from every signal generated
/// by each SignalProducer returned from apply() except `ActionError.disabled`.
public let events: Signal<Event<Output, Error>, NoError>
要观察成功的值,您需要订阅values
并使用observeValues
:
self.viewModel?.getListAction
.values
.take(during: lifetime)
.observeValues { [weak self] value in
// always successful
}
如果您想观察错误,可以订阅errors
并使用observeValues
。
self.viewModel?.getListAction
.errors
.take(during: lifetime)
.observeValues { [weak self] error in
// error event
}