Edwar D Day
06/15/2022, 6:28 AMnull
. I thought of something like that (for 2 `Flow`s):
fun <T : Any> takeFirstNotNull(flow1: Flow<T?>, flow2: Flow<T?>): Flow<T?> {
return flow1.transform {
if (it != null) emit(it) else emitAll(flow2)
},
}
Is there a simpler solution for this (especially, if this might be done for more `Flow`s)?Joost Klitsie
06/15/2022, 7:09 AMJoost Klitsie
06/15/2022, 7:11 AMfun <T : Any> takeFirstNotNull(flow1: Flow<T?>, flow2: Flow<T?>): Flow<T?> {
return flow1.takeWhile { it != null }.onCompletion { exception ->
if (exception == null) {
emitAll(flow2)
}
}
}
Joost Klitsie
06/15/2022, 7:13 AMfun <T : Any> takeFirstNotNull(flow1: Flow<T?>, flow2: Flow<T?>): Flow<T?> {
return flow1.takeWhile { it != null }.concatOnCompletion(flow2)
}
fun <T> Flow<T>.concatOnCompletion(other: Flow<T>) = onCompletion { exception ->
if (exception == null) {
emitAll(other)
}
}
Joost Klitsie
06/15/2022, 7:13 AMEdwar D Day
06/15/2022, 7:15 AMnull
value, get the values from source 2, as long as the value in source 1 stays null
.
Maybe as background info, my sources are `StateFlow`s, if this would make a difference.Joost Klitsie
06/15/2022, 7:16 AMfun <T : Any> takeFirstNotNull(flow1: Flow<T?>, flow2: Flow<T?>): Flow<T?> {
return combine(flow1, flow2) { value1, value2 -> value1 ?: value2 }
}
Joost Klitsie
06/15/2022, 7:18 AMJoost Klitsie
06/15/2022, 7:19 AMEdwar D Day
06/15/2022, 7:20 AMJoost Klitsie
06/15/2022, 7:22 AMtransformLatest
Joost Klitsie
06/15/2022, 7:23 AM