I have a ViewController in which on init() I create a hot stream using PublishSubject . Then I pass the stream to my ViewModel using stream.asObservable() in viewDidLoad() , since the ViewModel has other dependencies, which are the streams generated from the views, so it must wait until the view binding is complete before creating the ViewModel . After creating the ViewModel I push the event in my ViewController into the stream, and then expect the ViewModel to respond to the event by disabling the asynchronous request (which was also wrapped by Rx).
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) } .... }
ViewModel:
class ExampleViewModel { init(stream: Observable<Bool>) { stream.flatMap { _ in doSomethingAsyncThatReturnsAnObservable() } } private func doSomethingAsyncThatReturnsAnObservable() -> Observable<CustomObject> { ... } }
My problem is that doSomethingAsyncThatReturnsAnObservable() is called twice when there is only one event inside the stream. I checked this fact using var count = 1; stream.subscribeNext { _ in print(count++) } var count = 1; stream.subscribeNext { _ in print(count++) } , which prints 1 .
Any idea on why subscribeNext() fires once on each event, but flatMap() fires twice?
source share