Hello all. I am trying to sort through a solution...
# getting-started
b
Hello all. I am trying to sort through a solution to ensure that I only have a single instance of a task running at a time. The task is a suspend function that runs with an IO coroutine. As new values come in I need to kick off the task, the task is such that it only cares about the last element coming in to do its processing. Reading up on channels I think I can accomplish this, however running into some unexpected results. Code example in thread.
Copy code
// 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.
s
Looks like maybe you just need to make
doTask
suspend, instead of launching a fresh coroutine
b
Thank you! Is a conflated channel the correct channel to use to receive/queue another input after the previous was sent and is in processing?
From what I read in docs, yes, however it is still a bit confusing