Skip to content

Instantly share code, notes, and snippets.

@elizarov
Created December 26, 2020 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elizarov/53e72ea1e6175a5c1e45e30ff29125ed to your computer and use it in GitHub Desktop.
Save elizarov/53e72ea1e6175a5c1e45e30ff29125ed to your computer and use it in GitHub Desktop.
FlowTransformOptimizations
// see https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/flow/operators/Transform.kt#L20
public inline fun <T> Flow<T>.filter(crossinline predicate: suspend (T) -> Boolean): Flow<T> = transform { value ->
if (predicate(value)) return@transform emit(value)
}
// see https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/flow/operators/Transform.kt#L47
public inline fun <T, R> Flow<T>.map(crossinline transform: suspend (value: T) -> R): Flow<R> = transform { value ->
return@transform emit(transform(value))
}
// Step 1. take
flow
.filter { foo(it) }
.map { bar(it) }
// Step 2. inline filter & map
flow
.transform { value -> if (foo(value)) emit(value) }
.transform { value -> emit(bar(value)) }
// Step 3. inline emit call accross transforms
flow.
transform { value -> if (foo(value)) emit(bar(value)) }
// Now we have just one merged intermediate operator instead of two
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment