0

To set the stage, I have 2 network calls, the 2nd one depends on the result of the 1st.

fun netCall1(): Observable<Data1>{...}

fun netCall2(data: Data1): Observable<Data2>{...}

How do I create a stream that subscribes to netCall1(), uses the result to subscribe to netCall2(), then merges the results of both calls and return that?

net1: --1--2----------3-------- 
net2: -----------a-b--c--------
res : -----------P(1,a)--P(2,b)-P(3,c)---------
(network calls may retry up to 3 times, P means Pair<Data1,Data2>)

This is my attempt, but I'm unsure how to merge the results together.

fun myAttempt(): Observable<Pair<Data1, Data2>>{
  Observable.just()
    .flatMap{ netCall1() }
    .flatMap{ data1 -> netCall2(data1) }
    // unsure how to proceed...
}

Is this possible?

Some Noob Student
  • 14,186
  • 13
  • 65
  • 103
  • Please [edit] your question to include a detailed description of how the data should be "merged". Provide a marble diagram if possible to show when the observables generate the data objects and how you want to combine them. – Progman Jan 15 '22 at 20:40
  • Which value from one observable is "merged" or combined with what value from the other observable. Please use different values in the marble diagram. Also explain and/or show an example how the `Pair` instance should be build when `net2` is producing new values when the `net1` observable is not producing any new values. It is unclear how the value from `net1` have an affect on the subscriptions and/or values from `net2`. It is unclear if a new observable for `net2` is returned/used or how they depends on each other. If necessary, show the source code of the `net1` and `net2` observables. – Progman Jan 15 '22 at 21:06
  • 1
    You might want to look into the `zip()` operator to build the `Pair` instance you want. – Progman Jan 16 '22 at 20:50
  • Recommended reading: https://github.com/ReactiveX/RxJava#dependent-sub-flows – akarnokd Jan 18 '22 at 10:12
  • @Progman I need to feed the response of the 1st call to the 2nd one as they are dependent, so I don't think I can use zip(). – Some Noob Student Jan 18 '22 at 20:47
  • @akarnokd the nested flatMap() idea looks promising; thanks. – Some Noob Student Jan 18 '22 at 20:48
  • @SomeNoobStudent It can look like https://pastebin.com/Bw0qSV8t, but it depends on your specific situation you have in your case. You might want to add a MCVE to show the system/requirements/restrictions you have. – Progman Jan 18 '22 at 21:06

0 Answers0