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

louiscad

10/22/2018, 12:41 PM
Yes @robin, you can do it this way:
Copy code
coroutineScope {
    val daemonLikeJob = launch { while (true) /* Do sth until everything is done */ }
    coroutineScope {
        launch { /* do work */ }
        launch { /* do work */ }
    }
    daemonLikeJob.cancel()
}
r

robin

10/22/2018, 12:44 PM
That requires me to define the deamon job first, which doesn't feel good to me - what if I want to start the daemon job from inside a function that doesn't know about the rest of the coroutine scope?
l

louiscad

10/22/2018, 1:03 PM
Don't you think it's risky to do it the other way around?
r

robin

10/22/2018, 2:30 PM
Not sure why that would be risky. Can you explain why you think so?
l

louiscad

10/22/2018, 2:43 PM
You may not know a function will launch a coroutine that has a larger scope. But I think that greatly depends on the implementation though
r

robin

10/22/2018, 3:10 PM
It won't be a larger scope, though, that's the whole point. It should get cancelled when the containing scope wants to finish.
l

louiscad

10/22/2018, 3:14 PM
I think you can get the job from the context (
val scopeJob = coroutineContext[Job]!!
), launch the daemon from
GlobalScope
or another global but custom scope, and call
scopeJob.invokeOnCompletion { daemonJob.cancel() }
r

robin

10/22/2018, 3:16 PM
That should work, thanks! Still feel it's a little hacky, but if there's no official support for this it's probably as good as I can do.
2 Views