RxJava: Can you give me a real live scenario using flatMap instead of a map

I cannot figure out when to use flatmap instead of a map, and I cannot find a good example. Can you come up with a good script to select a flat map above the map?
Thank you

+4
source share
1 answer

For example, we want to make 2 requests, A and B, over the Internet. However, query B must be requested after query A ends because query B needs some result from query A. This is a good scenario flatMap. Examples of codes are as follows:

interface Movie {

}

interface UserInfo {
    List<Long> getFavoriteMovies();
}

public Observable<UserInfo> requestUserInfo(long userId) {
    // ...
}

public Observable<List<Movie>> requestMovieList(List<Long> movieIds) {
    // ...
}

public Observable<List<Movie>> requestUserMovieList(long userId) {
    return requestUserInfo(userId).flatMap(new Func1<UserInfo, Observable<List<Movie>>>() {
        @Override
        public Observable<List<Movie>> call(UserInfo user) {
            return requestMovieList(user.getFavoriteMovies());
        }
    });
}

, Ben Christensen slide RxJava: https://speakerdeck.com/benjchristensen/rxjava-goto-aarhus-2013

+4

Source: https://habr.com/ru/post/1543287/


All Articles