jewnbug97
jewnbug97

Reputation: 327

Chaining observables (that are network requests)

I have a network request called login that returns an Observable<UserInfo>. I need to make another API call from that result based on whether the data returned from login has a count > 1, otherwise, I just need to go to a different view controller. I’m trying to use flatMapLatest to do the check for the first request login and make the next network call jobStates (which returns an Observable<JobState>, but I don’t think I’m arranging them correctly. Any ideas? Is there a better / easier way to do this?

Here's what it looks like: enter image description here

Upvotes: 2

Views: 264

Answers (1)

Daniel T.
Daniel T.

Reputation: 33967

I would expect to see something like this:

func login() {
    let loginResult = networkService
        .login(login: usernameTextField.text!, password: passwordTextField.text!)
        .share()

    loginResult
        .filter { $0.count > 1 }
        .subscribe(onNext: { userInfo in
            // stop here and go to a different view with userInfo data
        })
        .disposed(by: disposeBag)

    let networkService = self.networkService // so you don't have to capture self below
    loginResult
        .filter { $0.count <= 1 }
        .flatMapLatest { networkService.jobStates(locationId: $0.locationId) }
        .subscribe(
            onNext: { data in
                // do whatever with data from second request
        },
            onError: { error in
                // if either request errors, you will end up here.

        })
        .disposed(by: disposeBag)
}

When you have two different possible outcomes, you need two different subscribes.

Upvotes: 2

Related Questions