Search code examples
androidfirebase-realtime-databasereactive-programmingrx-java2rx-kotlin

How do I avoid .zip(stream1, stream2, BiFun) subscribing to stream1 twice, when stream2 is based on stream1?


I am using firebase in android with some complex data. I need to save references and I'm getting problems with my zip operation, or the way I'm handling RX overall.

I want to create a new A object with information about a certain B, and update my B object to have information about the created A. When the firebase operations have both been successful I will return the Single<A>

val singleA = firebaseCall(A("ABC", bKey))

val singleB = singleA.flatMap{ a -> firebaseCall(B(aKey)) }

return Single.zip(singleA, singleB, BiFunction { a, b -> a })

When going through logcat I can see that SingleA get subscribed to twice, and pushes twice to firebase. I want to avoid this!

So, how can I use a zip function on A and B, when B is dependent on A; and not have A being performed twice?


Solution

  • You don't really need zip for this as you can simple map a back:

    val singleA = firebaseCall(A("ABC", bKey))
    
    return singleA.flatMap{ a -> firebaseCall(B(aKey)).map { a } }