I had a bunch of observables that I wanted to merge into a single observable and then subscribe to it. I knew that I could use merge but had an unknown sequence size of observables, so how could I do it? Easy I can use the merge and fold functions:-
val obs1: Observable[Int] = Observable.from(Seq(1,2,3,4,5)) val obs2: Observable[Int] = Observable.from(Seq(6,7,8,8,10)) val obs3: Observable[Int] = Observable.from(Seq(11,12,13,14)) val totalObservable = Seq(obs1, obs2, obs3) .fold(Observable.just[Int]())((a,b) => a.merge(b)) totalObservable.foreach(x => println(s"This is the value ${x}"))
The fold takes in an initial value, in this case “Observable.just[Int]()” followed by the aggregation function “a.merge(b)”. It took me about 30 mins to figure out the syntax, especially around the initial value but the code is clean and clear.