Reduce code in RxJava’s combiners

Alexander Zhdanov
AndroidPub
Published in
2 min readOct 23, 2018
My favourite library in Android development

RxJava is widely used in many Android applications and it’s common use case where data need to be combined from two or more data sources.

This may be done via variety of RxJava operators like zip() or zipWith()or combineLatest() or withLatestFrom() and so on.

The last parameter of these operators is combiner function that is used to combine data from several sources into one data-item.

Often we just need all data that come from all sources and we create Pair or Triple with code like this:

obs1.withLatestFrom(
obs2,
obs3,
Function3 { t1: Int, t2: Int, t3: Int -> Triple(t1, t2, t3) }
)

Or sometimes we need to keep only second data-item of two items in situation like this:

obs1.withLatestFrom(obs2, BiFunction { _: Int, t2: Int -> t2 })

This looks a bit verbose and redundant. Too many code for such a simple operation.

But we can reduce it via combiners for widely used operations like create Pair or Triple:

fun <T, U> makePair() = BiFunction { t: T, u: U -> Pair(t, u) }fun <T, U, V> makeTriple() = Function3 { t: T, u: U, v: V -> 
Triple(t, u, v)
}

This function can be used easily:

val o12 = obs1.withLatestFrom(obs2, makePair())
val o123 = obs1.withLatestFrom(obs2, obs3, makeTriple())

Also functions that allows keep only first or only second of two data-items can be created:

fun <T, U> firstOfTwo() = BiFunction { t: T, _: U -> t }
fun
<T, U> secondOfTwo() = BiFunction { _: T, u: U -> u }

With three elements the situations is similar:

fun <T, U, V> thirdOfThree() = Function3 { _: T, _: U, v: V -> v }fun <T, U, V> lastTwoOfThree() = Function3 { _: T, u: U, v: V ->
Pair(u, v)
}

Usage is also simple:

val o2 = obs1.withLatestFrom(obs2, secondOfTwo())
val o3 = obs1.withLatestFrom(obs2, obs3, thirdOfThree())

That’s it.
Use it. Happy coding.

--

--