6

我有一个ViewController在其中init()使用PublishSubject. ViewModel然后我将流传递给我stream.asObservable()viewDidLoad(). 创建后,我将我的事件推送到流中,然后期望 ViewModel 通过触发异步请求(也已用 Rx 包装)来对事件做出反应。ViewModelViewModelViewModelViewController

视图控制器:

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?

4

1 回答 1

5

This is because flatMap called on every subscription.

If you want it to be called once use shareReplay(1)

于 2016-02-01T20:28:10.523 回答