Billy Newman
12/20/2023, 9:39 PMBilly Newman
12/20/2023, 9:46 PM// Not sure if this is the right channel to use.
// I want to process one element from the queue at a time,
// and allow for one more element to be added while I process.
// If a new element comes in while processing I want the channel
// drop the oldest and queue the newest
private val channel = Channel<Long>(Channel.CONFLATED)
...
// on init of my class collect the flow and listen for changes
lifecycleScope.launch {
channel.receiveAsFlow().collect { value ->
doTask(value)
}
}
// called multiple times frequently, trying to ensure that when
// sending to the channel, the channel will finish its previous // processing before starting the next with the latest value sent
fun onValueChanged(value: Long) {
channel.send(value)
}
private fun doTask(value: Long) {
lifecycleScope.launch {
// call some long running processing function
otherClass.process(value)
}
}
class OtherClass() {
suspend fun process = withContext(Dispatchers.IO) {
// process on IO thread
}
}
When I run I am seeing the channel send values, however it is not waiting for the process function to complete before receiving another value. Any help in the right direction would be greatly appreciated.Sam
12/20/2023, 9:56 PMdoTask
suspend, instead of launching a fresh coroutineBilly Newman
12/20/2023, 10:10 PMBilly Newman
12/20/2023, 10:10 PM