capt.swag
capt.swag

Reputation: 10661

RxJava, combining two observables and emitting second observable

I'm making two network requests, say N1 and N2. These are two separate requests which are not dependent on each other.

N1

    Observable<GenresListResponse> genresListResponseObservable =
            tmdbInterface.getGenresList(BuildConfig.API_KEY);

N2

    Observable<NowPlayingMoviesListResponse> nowPlayingMoviesListResponseObservable =
            tmdbInterface.getNowPlayingMovies(BuildConfig.API_KEY);

Once I get the response of both, I need to find genres of each now playing movie from the genres list and set genre to each item in the now playing movies list. Finally, emit Observable NowPlayingMoviesListResponse which now contains the genres as String.

NowPlayingMoviesList POJO class contains setGenre(String genre) which can be used to set the genre after it's deduced from genresList.

For better understanding, this is the JSON value coming from the server.

genre.json

{
    "genres": [
        {
            "id": 28,
            "name": "Action"
        },
        {
            "id": 12,
            "name": "Adventure"
        }
    ]
}

now_playing_movie.json

{
    "results": [
        {
            "vote_count": 3290,
            "id": 346364,
            "original_language": "en",
            "original_title": "It",
            "genre_ids": [
                18,
                27,
                53
             ]
        }
    ]
}

Now In the movies model class, I have setGenres(String genre) which sets the genre after comparing ids with the response of the genres request.

Upvotes: 0

Views: 909

Answers (1)

charlag
charlag

Reputation: 1037

There are multiple ways to wait for multiple Observable streams. If you want to emit only when every stream emitted element - then there's a Zip operator. If you want to wait for all your streams to emit at least once but after then you want every emission to trigger with the last values - there's a CombineLatest operator.

As far as I can tell, each of your streams emit only once, so I guess you need Zip. I would also recommend making your streams Single (modern Retrofit adapters do this).

Upvotes: 1

Related Questions