Java – Converts Observable of List to List of Observables and merges in RxJava

Converts Observable of List to List of Observables and merges in RxJava… here is a solution to the problem.

Converts Observable of List to List of Observables and merges in RxJava

I’m learning Java and Android by creating a Hacker News reader app.

What I want to do is:

  1. Send a request to /topstories to return Observable<List<int>> when issued
    The request is complete.
  2. Map storyId to Observable<Story> respectively
  3. Combine Observables into a single entity that issues a List<Story> when all requests are completed.

Code:

  private Observable<Story> getStoryById(int articleId) {
    BehaviorSubject<Story> subject = BehaviorSubject.create();
     calls subject.onNext on success
    JsonObjectRequest request = createStoryRequest(articleId, subject);
    requestQueue.add(request);
    return subject;
  }

public Observable<ArrayList<Story>> getTopStories(int amount) {
    Observable<ArrayList<Integer>> topStoryIds = (storyIdCache == null)
      ? fetchTopIds()
      : Observable.just(storyIdCache);

return topStoryIds
      .flatMap(id -> getStoryById(id))
       some magic here
  }

Then we’ll use it like this:

getTopStories(20)
  .subscribe(stories -> ...)

Solution

You can try something like this

Observable<List<Integers>> ids = getIdsObservable();
Single<List<Story>> listSingle =
            ids.flatMapIterable(ids -> ids)
            .flatMap(id -> getStoryById(id)).toList();

You can then subscribe to that Single to get a List<Story>

Related Problems and Solutions