Joakim Sjöstedt
Joakim Sjöstedt

Reputation: 948

How do I observe two rx sequences and subscribe with two closure arguments?

I want to observe two behaviorRelays with a single observer, wait for both relays to emitt their values, then in the subscription have two seperate closure arguemts, one for each relay. Something like this:

let one = firmwareService.basicIODeviceUnit.compactMap { $0?.canBeUpdated }
let two = firmwareService.motorDeviceUnit.compactMap { $0?.canBeUpdated }
        
Observable.of(one, two).flatMap{ $0 }.subscribe(onNext: { a, b in
    print("--", a, b)
}).disposed(by: disposeBag)

The above code isn't allowed. The operators like merge or zip seem to bundle both relays into a single closure argumet so I guess they won't work. What do I use?

I have looked through this thread, so it should be possible, but I can't wrap my head around it since I use swift RxJS Subscribe with two arguments

Upvotes: 1

Views: 470

Answers (2)

Daniel T.
Daniel T.

Reputation: 33967

I'm not sure what you mean because zip does exactly what you want. So does combineLatest.

let one = firmwareService.basicIODeviceUnit.compactMap { $0?.canBeUpdated }
let two = firmwareService.motorDeviceUnit.compactMap { $0?.canBeUpdated }

Observable.zip(one, two)
    .subscribe(onNext: { a, b in
        print("--", a, b)
    })
    .disposed(by: disposeBag)

Upvotes: 1

Shivam Gaur
Shivam Gaur

Reputation: 541

you can use combineLatest:

combineLatest is an operator which you want to use when value depends on the mix of some others Observables. When an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified closure and emit items based on the results of this closure.

For reference follow this - combineLatest meduim link

Upvotes: 0

Related Questions