1

Can someone help me find the proper solution for this problem I face?

  1. I have a backend service that give me Observables of the data I need, which are Events.
  2. Form the Event I can get an EventGroup, which contains Ids of all events in the same group.
  3. Next I can get all the Events that are part of this group.

However, I get a Observable<List<Observable<Event>>>, where I'd like to get a Observable<List<Event>>. How can I achive this, without actually subscribing to the nested Observables?

val events : Observable<List<Observable<Event>>> = 
   eventProvider.observable
      .flatMap { myBackend.getEventGroup(it.eventGroupId) }
      .map { 
         it.eventIds.map { myBackend.getEvent(it) } 
      }

TL:DR

How do I get Observable<List<X>> from a Observable<List<Observable<X>>>?

Endran
  • 1,627
  • 1
  • 10
  • 15

2 Answers2

1

flatMap twice and then use toList:

Observable<List<Observable<X>> source = ...

Observable<Observable<X>> step1 = source.flatMapIterable(v -> v);

Observable<X> step2 = step1.flatMap(v -> v);

Observable<List<X>> result = step2.toList();

Note that this requires all participating Observables to be finite.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • All the `Observables` are infinite, so I cannot directly use your approach. However, your answer did lead me to the direction I needed, because I could convert on of the `Observables` into a finite one. Thanks :) – Endran Jun 23 '17 at 13:09
0

I figured it out, inspired by the answer of @akarnokd. @akarnokd answer expects all sources to be finite, but mine are all infinite. However I can live with partially infinite as well.

I need my resulting Observable to be infinite, because I want to receive a new list of Events whenever the eventProvider.observable emits something. However, I'm ok with the events I get back via myBackend.getEvent(it) to behave as a finite source.

val events : Observable<List<Event>> = 
   eventProvider.observable
      .flatMap { myBackend.getEventGroup(it.eventGroupId) }
      .map { it.eventIds.map { myBackend.getEvent(it) } }
      .map { it.toObservable().flatMap { it.first() }.toList() }
      .flatMap { it }
Endran
  • 1,627
  • 1
  • 10
  • 15