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

mbonnin

01/03/2019, 2:43 PM
Copy code
fun sampleProducer(): Channel<Int>{
        val channel = Channel<Int>(UNLIMITED)
        val thread = Thread {
            var i = 0
            while(true) {
                channel.offer(i++)
                Thread.sleep(1000)
            }
        }

        // the bellow doesn't work but it would be nice if it did
        channel.doOnCancel {
              // terminate the thread
        }
        thread.start()

        return channel
    }

    @Test
    fun main() {
        val channel = sampleProducer()

        runBlocking {
            for (i in 1..5) {
                System.out.println("received: ${channel.receive()}")
            }
            channel.cancel()
            // How can I make sure the thread is joined here or very shortly after here ?
        }
    }
Hello everyone, I'm trying to bridge an existing library and coroutines. The library has a traditional callback API that I would like to expose as a coroutine channel. It's working well but I cannot find a way to propagate the cancellation to the library. The problem is equivalent to the snippet above. Any idea how I could achieve this ?
d

Dico

01/03/2019, 3:18 PM
invokeOnCompletion
You can call this on a job
If you use an actor, that would work
I am not sure if a channel has it too
m

mbonnin

01/03/2019, 3:19 PM
There's
channel.invokeOnClose
Looks like it's working 🙂
Thanks !
👍🏻 1
2 Views