Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava, good use case of flatmap

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

like image 944
EyeQ Tech Avatar asked Aug 07 '15 06:08

EyeQ Tech


1 Answers

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*/});
like image 81
Aleksandr Avatar answered Oct 11 '22 14:10

Aleksandr