我有一个ViewController
在其中init()
使用PublishSubject
. ViewModel
然后我将流传递给我stream.asObservable()
在viewDidLoad()
. 创建后,我将我的事件推送到流中,然后期望 ViewModel 通过触发异步请求(也已用 Rx 包装)来对事件做出反应。ViewModel
ViewModel
ViewModel
ViewController
视图控制器:
class ExampleViewController: ViewController {
....
private let exampleStream: PublishSubject<Bool>
init() {
self.exampleStream = PublishSubject<Bool>()
}
viewDidLoad() {
self.viewModel = viewModelFactory.create(exampleStream.asObservable())
self.exampleStream.onNext(true)
}
....
}
视图模型:
class ExampleViewModel {
init(stream: Observable<Bool>) {
stream.flatMap { _ in
doSomethingAsyncThatReturnsAnObservable()
}
}
private func doSomethingAsyncThatReturnsAnObservable() -> Observable<CustomObject> { ... }
}
我的问题是,doSomethingAsyncThatReturnsAnObservable()
当流中只有一个事件时,它被调用了两次。var count = 1; stream.subscribeNext { _ in print(count++) }
我已经通过使用which prints检查了这一事实1
。
Any idea as to why subscribeNext()
fires once on each event but flatMap()
fires twice?