https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

acando86

12/13/2018, 1:08 PM
What's the best way to keep draining continuously a receivechannel, cancel whatever task the receiver is doing (if any) and start processing the latest messages as soon as they reaches the channel?
d

Dico

12/13/2018, 1:42 PM
I don't understand. Can you try to clarify what you're trying to achieve? I just don't understand how the 3 things add up in a single situation
a

acando86

12/13/2018, 2:14 PM
Copy code
for (newData in channel) {
          heavyComputation(newData)
            // This process is expensive,  I want to keep receiving newData as soon as they are available, cancel the heavy computation and start a new one with fresh data

        }
highly simplified ☝️
d

Dico

12/13/2018, 2:22 PM
And risk the computations never being completed? Weird use case, but that's fine.
Copy code
fun CoroutineScope.heavyComputation(data)...


val parent = SupervisorJob()
val scope = new coroutine scope with job as context
for (data in channel) {
  parent.cancelChildren()
  scope.heavyComputation(data)
}
That seem right to you?
In heavyComputation() you can
launch
or
async
or whatever, make sure you also have an appropriate dispatcher in the scope
Also it sounds like you probably want to use a conflated channel :)
6 Views