gpt4 book ai didi

swift - ReactiveSwift Action observeResult 没有像应该的那样返回失败

转载 作者:搜寻专家 更新时间:2023-11-01 07:13:20 25 4
gpt4 key购买 nike

现在我对 ReactiveSwift 很感兴趣,并尝试将其添加到项目的网络操作中。但是observeResult方法的action返回类型存在一些问题。

查看模型:

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)
}
}
}
}

从 Controller 我试过这样管理它:

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 方法返回失败,情况如下:

方法返回成功,但事实并非如此。应该是失败。请让我了解这个主题的问题所在。

最佳答案

您观察到的 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
}

关于swift - ReactiveSwift Action observeResult 没有像应该的那样返回失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43645958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com