Tim Malseed
03/01/2023, 1:21 AMList<Flow<String?>>
I’d like to emit the latest value from the first flow in the list - unless that value is null, in which case I’d like to move to the next flow.
Does anyone know how to achieve this?ephemient
03/01/2023, 1:42 AMTim Malseed
03/01/2023, 1:43 AMephemient
03/01/2023, 1:43 AMephemient
03/01/2023, 1:45 AMmerge(flows.map { it.filterNotNull() })
this of course does not reflect the ordering of the original listTim Malseed
03/01/2023, 2:12 AMChris Fillmore
03/01/2023, 3:14 AMI want to continue receiving the latest values if the flows continue to emit.This is what
collect
does.
I think you’re right, you’re not sure what you want. Let’s take a step back. What data is in your flows and what’s your use case? What are you trying to do?Tim Malseed
03/01/2023, 3:17 AMval flows: List<Flow<String?>>
fun getValue(): Flow<String?> {
return combine(dataSources.map { it.getValue() }) { values ->
values.first { it != null }
}
}
Tim Malseed
03/01/2023, 3:18 AMTim Malseed
03/01/2023, 3:20 AMephemient
03/01/2023, 3:21 AMChris Fillmore
03/01/2023, 3:22 AMephemient
03/01/2023, 3:22 AMTim Malseed
03/01/2023, 3:22 AMChris Fillmore
03/01/2023, 3:23 AMTim Malseed
03/01/2023, 3:23 AMTim Malseed
03/01/2023, 3:24 AMChris Fillmore
03/01/2023, 3:25 AMTim Malseed
03/01/2023, 3:26 AMTim Malseed
03/01/2023, 3:26 AMTim Malseed
03/01/2023, 3:26 AMTim Malseed
03/01/2023, 3:27 AMstreetsofboston
03/01/2023, 4:09 AMflowOfFlows =
flow {
listOfFlows.forEach {
emit(it.takeWhile { it != null })
}
}.flattenConcat()
I haven't tried this at all, but if I understand your problem, this could be a solution.
First change your list of flows into a flow of flows.
Make sure that each flow ends/completes when null is emitted (return new flows that complete this way using takeWhile).
And now that all inner flows complete, you can call flattenConcat to concatenate them all.ephemient
03/01/2023, 6:48 AMlistOf(
flow {
emit(null)
delay(100)
emit("a")
},
flow {
emit("b")
}
)
then the combine
method will produce "b", "a" while yours will produce "a", "b"streetsofboston
03/01/2023, 11:50 AMephemient
03/01/2023, 11:27 PMfun <T : Any> List<Flow<T?>>.switchToFirstNonNull(): Flow<T> = foldRight(emptyFlow()) { flow, fallback ->
flow.flatMapLatest { if (it != null) flowOf(it) else fallback }
}
that results in subscriptions to the later flows only when the earlier flows emit null
. of course, this can result in repeated re-subscriptions to the later flows