fun <T> Flow<T>.orElse(fn: () -> T): Flow<T> {
return flow {
var isEmpty = true
collect { value ->
isEmpty = false
emit(value)
}
if (isEmpty) emit(fn())
}
}
e
Erik
03/31/2020, 6:40 AM
Since you must have collected the entire flow to know it's empty, why not collect it as a list first and then use a default value if the list is empty?
Copy code
val emptyFlow = emptyFlow<Int>()
val nonEmptyFlow = flowOf(1, 2, 3)
val default = listOf(0)
println(emptyFlow.toList().ifEmpty { default }) // [0]
println(nonEmptyFlow.toList().ifEmpty { default }) // [1, 2, 3]