gmoraleda
gmoraleda

Reputation: 1943

RxSwift: Subscribe to Observable.zip. Handle result as tuple?

I'm trying to combine two network requests with the zip function. These two requests rely on another one (getInfoA).

This is the code I'm working with:

IoC.networkProcessService.getInfoA(with: identifier)
            .map { infoA -> Observable<(InfoB, InfoC)> in

                return Observable.zip(
                    IoC.networkProcessService.getInfoB(with: infoA),
                    IoC.networkProcessService.getInfoC(with: infoA) 
                { return ($0, $1) }

            }
            .subscribe(onNext: { result in
                print(result)

               // result is of type Observable<(InfoB, InfoC)>...

            }, onError: { error in
                Logger.main.log(category: [.network, .error], arguments: error.localizedDescription)

            })
            .disposed(by: disposeBag)

I would expect that result (in the subscribe block) is a tuple and that I'm able to access infoB and infoC.

But it's not. Is subscribe the right operator to access the tuple from zip?

Upvotes: 3

Views: 2039

Answers (1)

Thanh Vu
Thanh Vu

Reputation: 1739

Just change map to flatMap, result will change to tuple instead Observable.

IoC.networkProcessService.getInfoA(with: identifier)
  .flatMap { infoA -> Observable<(InfoB, InfoC)> in

    return Observable.zip(
      IoC.networkProcessService.getInfoB(with: infoA),
      IoC.networkProcessService.getInfoC(with: infoA)
      { return ($0, $1) }

  }
  .subscribe(onNext: { result in
    print(result)

    // result is of type (InfoB, InfoC)

  }, onError: { error in
    Logger.main.log(category: [.network, .error], arguments: error.localizedDescription)

  })
  .disposed(by: disposeBag)

Upvotes: 3

Related Questions