Search code examples
javarx-java

RXJava persist return value of previous flatMap


In RX JAVA(java8), how can I persist value of previous flatMap or map.

public void createAccount(]) {
    JsonObject payload = routingContext.getBodyAsJson();
    socialService.getOAuthToken(payload)
            .flatMap(token -> {
                return getAllAccounts(token);
            })
            .flatMap(accounts -> {
                // Save accounts with TOKENS
            })
            .subscribe(accountID -> {
                  response(accountID);
            );
}

So in above code, in second flatMap how can I get the token from previous flatMap.


Solution

  • You have to zip account and token and pass it to the next Stream operation.

    //Note you have to replace T, A with the right type
    socialService.getOAuthToken(payload).flatMap(token -> getAllAccounts(token)
            .map(account -> new SimpleImmutableEntry<T, A>(token, account)))
         .flatMap(accounts -> /* accounts.getKey() -> token, accounts.getValue() -> account */)
         .subscribe(accountId -> response(accountId));