Search code examples
rx-swiftswift5

Intercept data from observable before binding it to another observer


I have a observable that emits data which looks something like this:

struct AlertData {
    let name: String
    let actionStream: PublishSubject<Void>
}

So when I receive AlertData from observable I directly bind it to another observer, which works fine. But before binding it to another observer, I wanted to get the 'actionStream' and get events from it.

So, this is how I emitting the AlertData:

let alertStream = PublishSubject<AlertData>()
alertStream.onNext(***)

This is the receiving part:

alertStream.bind(to: anotherObserver).disposed(by: disposeBag)

But before binding alertStream to anotherObserver, I wanted the actionStream which is inside the AlertData and receive any events emitted from it. What is the proper way of doing it?


Solution

  • let actionStream = alertStream
        .flatMap { $0.actionStream.asObservable() }
    

    You might not actually want flatMap (which acts as a flat map merge) specifically. Look into the variations on flatMap and see which one is most suitable for your particular situation: RxSwift’s Many Faces of FlatMap