spierce7
03/31/2020, 4:54 AMFlow
if nothing else is output, and it completes, what’s the best way to do that?Zach Klippenstein (he/him) [MOD]
03/31/2020, 4:59 AMspierce7
03/31/2020, 5:02 AMonCompletion
, but it doesn’t tell me if other items have been emitted.spierce7
03/31/2020, 5:03 AMreturn flow {
var isEmpty = true
emitAll(
baseFlow
.onEach { isEmpty = false }
.onCompletion {
if (isEmpty) {
emit(defaultData)
}
}
)
}
araqnid
03/31/2020, 6:35 AMcollect
rather than using onEach
and onCompletion
.. just a stylistic difference, I thinkaraqnid
03/31/2020, 6:37 AMfun <T> Flow<T>.orElse(fn: () -> T): Flow<T> {
return flow {
var isEmpty = true
collect { value ->
isEmpty = false
emit(value)
}
if (isEmpty) emit(fn())
}
}
Erik
03/31/2020, 6:40 AMval 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]
elizarov
03/31/2020, 7:39 AM