1

I'm trying to observe a Variable and when some property of this variable fits a condition, I want to make an "observable" API call and bind the results of that call with some UI element. It is working the way I present it here, but I'm having the thought that it could be implemented way better, because now I'm nesting the subscription methods:

self.viewModel.product
    .asObservable()
    .subscribe { [weak self](refreshProduct) in

        self?.tableView.reloadData()
        self?.marketProduct.value.marketProduct = refreshProduct.element?.productId

        if refreshProduct.element?.stockQuantity != nil {

            self?.viewModel.getUserMarketCart()
                .map({ (carts) -> Bool in
                    return carts.cartLines.count > 0
                }).bind(onNext: { [weak self](isIncluded) in
                    self?.footerView.set(buyable: isIncluded)
                }).disposed(by: (self?.disposeBag)!)
        }
    }.disposed(by: disposeBag)

Is there any other way to do this? I can get a filter on the first observable, but I don't understand how I can call the other one and bind it on the UI.

NOTE: I excluded a few other lines of code for code clarity.

sheinix
  • 167
  • 1
  • 13

1 Answers1

0

A typical solution would be using .switchLatest() as follows.

  • create *let switchSubject = PublishSubject<Observable<Response>>()"
  • bind UI to it's latest value: switchSubject.switchLatest().bind(...
  • update 'switchSubject' with new requests: switchSubject.onNext(newServiceCall)
Maxim Volgin
  • 3,957
  • 1
  • 23
  • 38