0

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?

vm345
  • 813
  • 12
  • 28
Yokich
  • 1,247
  • 1
  • 17
  • 31
  • Why do you need to zip them? Any emission from A will be flatMapped and you can just subscribe to B – elmorabea Dec 27 '17 at 13:45
  • The method signature should return `Single`, that's why – Yokich Dec 27 '17 at 15:17
  • You get double subscriptions because your source of emissions in both cases is the same, which is firebaseCall(A("ABC", bKey)), then you zip it with itself but flatMapped, if you want to only "map" the return type, then just use map operator – elmorabea Dec 27 '17 at 15:21

1 Answers1

1

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 } }
akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • True, that's a nice solution. I did something similar that I'm using right now, But for an educational purpose. Why do the zip makes the `singleA` subscribe twice, and how could I avoid it? – Yokich Dec 27 '17 at 14:21
  • I did some research and it is simply the case that `zip` subscribes to both sources and then does its magic, so it's easily explained why the first stream subscribes twice. I'll mark this as the answer; being a clean solution – Yokich Dec 27 '17 at 15:29