Filter items from Iterable with Flow
This file contains 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
suspend fun <T, R : Iterable<T>> Flow<Iterable<T>>.filterIterable(predicate: suspend (T) -> Boolean): Flow<R> = | |
transform { | |
flow { | |
val emitted = arrayListOf<T>() | |
for (item in it) { | |
if (predicate(item)) { | |
emitted.add(item) | |
} | |
} | |
emit(emitted) | |
} | |
} | |
suspend fun <T> Flow<Iterable<T>>.filter(predicate: suspend (T) -> Boolean): Flow<T> = | |
transform { | |
flow { | |
for (item in it) { | |
if (predicate(item)) { | |
emit(item) | |
} | |
} | |
} | |
} | |
suspend fun <T, R : Iterable<T>> Flow<Iterable<T>>.reversedIterable(): Flow<R> = | |
transform { | |
flow { | |
emit(it.reversed()) | |
} | |
} | |
suspend fun <T> Flow<Iterable<T>>.reverse(): Flow<T> = | |
transform { | |
flow { | |
val emitted = LinkedList(it.toList()) | |
while (emitted.isNotEmpty()) { | |
emit(emitted.poll()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment