Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Last active October 5, 2020 23:04
Embed
What would you like to do?
Filter items from Iterable with Flow
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