https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

julian

07/02/2020, 2:13 AM
Does Flow have something like RxJava's
compose
operator? (Rather than operating individual items emitted by a Flow, it would operate on the Flow itself, returning a new composed Flow.)
o

octylFractal

07/02/2020, 2:14 AM
no, it's basically implemented by normal composition
👍🏾 1
e.g. if you wanted a custom `mapAndFilter`:
Copy code
fun <T, V> Flow<T>.mapAndFilter(map: suspend (T) -> V, filter: suspend (V) -> Boolean): Flow<V> {
  return map(map).filter(filter)
}
or custom logic:
Copy code
fun Flow<Int>.addThreeToEveryThird(): Flow<Int> {
  val original = this
  return flow {
     var i = 0
     original.collect {
       i++
       when (i % 3) {
         0 -> emit(it + 3)
         else -> emit(it)
       }
     }
  }
}
j

julian

07/02/2020, 2:18 AM
Yup! You beat me to it, was just about to write: Ok. I see how I could use an extension function on
Flow
that could return a transformed
Flow
.
Thanks @octylFractal!
👍 1
l

louiscad

07/02/2020, 5:53 AM
Are you looking for the
combine
operator? This one exists as a top level function, and an extension of
Flow<*>
.
o

octylFractal

07/02/2020, 5:55 AM
No, RxJava
compose
is basically as described above -- it allows the mapping of a
Flow<T>
to
Flow<V>
as a whole, not based on intermediate elements. It is also not a merging device.
👍🏾 1
5 Views