reactormonk
06/11/2024, 1:52 PMStateFlow
in a select
statement? The IDE doesn't seem to think onAwait
exists.ross_a
06/11/2024, 2:19 PMcoroutineScope {
val channel1 = stateFlow1.produceIn(this)
val channel2 = stateFlow2.produceIn(this)
// often whileSelect when dealing with streams
select {
channel1.onReceiveCatching { result -> }
channel2.onReceiveCatching { result -> }
}
// Remember to close
channel1.close()
channel2.close()
}
There's not much point in an onAwait
for StateFlow
as it always has a value immediately accessible with .value
- Unless you are combining it with filter
in which case you could do
coroutineScope {
val async1 = async { stateFlow1.filterNotNull().first() }
val async2 = async { stateFlow2.filterNotNull().first() }
select {
async1.onAwait { result -> }
async2.onAwait { result -> }
}
}
reactormonk
06/11/2024, 2:35 PMreactormonk
06/11/2024, 3:43 PMval transientToStandby = tvState.filter { it is TVState.TransientToStandby }.produceIn(this)
val standby = tvState.filter { it is TVState.Standby }.produceIn(this)
val timeout = produce<Unit> { delay(5.seconds); send(Unit) }
select<Unit> {
transientToStandby.onReceive {
}
standby.onReceive {
}
timeout.onReceive {
}
}
ross_a
06/11/2024, 3:58 PMwhen (val result = withTimeoutOrNull(5.seconds) {
tvState.filter { it is TVState.TransientToStandby || it is TVState.Standby }.first()
}) {
TVState.TransientToStandby -> {}
TVState.Standby -> {}
null -> {}
}
ross_a
06/11/2024, 4:00 PMselect
also provides an onTimeout
method if you don't want to create your own produce
blockreactormonk
06/11/2024, 4:01 PMselect
version, reads better.