'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 1:[1]
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));
Solution 2:[2]
Kotlin solution based on the solution by @Flown:
socialService.getOAuthToken(payload)
.flatMap { token ->
getAllAccounts(token)
.map { account -> Pair(token, account) }
}
.flatMap { (token, account) -> /* Use values here */ }
.subscribe { accountId -> response(accountId) }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Flown |
| Solution 2 | molundb |
