简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM