Created
December 26, 2020 09:36
-
-
Save elizarov/53e72ea1e6175a5c1e45e30ff29125ed to your computer and use it in GitHub Desktop.
FlowTransformOptimizations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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