Skip to content

Instantly share code, notes, and snippets.

@NikolaDespotoski
Last active October 5, 2020 23:04
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 NikolaDespotoski/ea8c1cec0fc19bf5f44aa740d6a0c290 to your computer and use it in GitHub Desktop.
Save NikolaDespotoski/ea8c1cec0fc19bf5f44aa740d6a0c290 to your computer and use it in GitHub Desktop.
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