I'm new to RxJava, often got confused by flatMap function. According to the doc, flatmap transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
Can someone give a good use case for it? Why transform the original Observable into Observables (plural) then turn them into a single Observable.
Why don't you just use 'map'?
If you give an example in Android that's awesome, otherwise plain Java is good enough. Thanks
I see tag Android
on your question. So, probably you should be familiar with Retrofit
.
Let's image that you have 2 methods:
public interface FoxreyRestApi {
@POST("/signin")
Observable<SignInResponse> signin(@Body SignInRequest request);
@GET("/user")
Observable<User> getUser(String accessToken);
}
You want to get user data, but you need accessToken
, which return is SignInResponse
.
You can do this:
1). Create your RestAdapter
.
2). Do queries one - after - another:
restAdapter.signin(request)
.flatMap(r -> restAdapter.getUser(r.getAccessToken()))
.subscribe(user -> {/*User your user*/});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With