spierce7
02/19/2021, 6:01 PMMarc Knaup
02/19/2021, 6:02 PMStateFlow
stops as usual.
But StateFlow
doesn’t stop collecting from upstream.Marc Knaup
02/19/2021, 6:02 PMspierce7
02/19/2021, 6:05 PMflow {
// Do download here
emit(progress)
}
Because then I’d be blocking my download thread with potentially backed up emit calls.spierce7
02/19/2021, 6:07 PMval stateFlow = MutableStateFlow()
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
// Do Download
stateflow.value = progress
}
return stateFlow
would solve that, but I don’t think the state flow would work here. Whoever collected from it would never stop collecting, right?spierce7
02/19/2021, 6:07 PMcomplete
the StateFlow
Marc Knaup
02/19/2021, 6:07 PMStateFlow
works perfect for download progress.
You can force the downstream collectors to stop collecting when the download is complete.Marc Knaup
02/19/2021, 6:09 PMMarc Knaup
02/19/2021, 6:10 PMcompleteWhenDone
on your StateFlow
Casey Brooks
02/19/2021, 6:10 PMflow { }
builder, this is a perfectly normal use-case, and is a better fit than StateFlow. Using .flowOn(<http://Dispatchers.IO|Dispatchers.IO>)
will allow the upstream producer to run on background threads, while the downstream collector will collect in the main thread.
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flow-on.htmlMarc Knaup
02/19/2021, 6:11 PMStateFlow
only when you actually have to maintain a state (i.e. the last 1+ values) for collectors 🙂kevin.cianfarini
02/19/2021, 6:56 PMBecause then I’d be blocking my download thread with potentially backed up emit calls.
offer
?kevin.cianfarini
02/19/2021, 6:58 PMflow
to channelFlow
and make the download progress a callback. Then offer from there. offer only emits events if the downstream collectors aren’t applying backpressureCasey Brooks
02/19/2021, 7:06 PM.conflate()
the flow, so emissions are simply dropped if the collector is slow and can’t keep up https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/conflate.html
Or .debounce()
to set a particular delay time between emissions, dropping the rest https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/debounce.htmlspierce7
02/19/2021, 7:09 PM.flowOn
?Casey Brooks
02/19/2021, 7:12 PM