What's the best practices when creating a scope sp...
# coroutines
c
What's the best practices when creating a scope specifically for cancellation control of a daemon?
Copy code
suspend fun runTask() {
    val childScope = CoroutineScope(currentCoroutineContext() + Job(currentCoroutineContext().job))

    SomeDaemon(childScope).run()

    // wait for some condition

    childScope.cancel()
}
I think this respects all structured concurrency constraints?
y
w
I think this respects all structured concurrency constraints?
Sorry for getting back to this, but this is my passion subject :) Structured Concurrency pretty much means only
coroutineScope
. I know it might sound idealistic at first, but trust me, you can do so much more with
coroutineScope
than you think :) Constructing a CoroutineScope manually is full of footguns, and should be reserved for complex low level situations. I'd have to get into details to explain why runTask currently breaks what you should expect of structured concurrency (which I would love to :) ), but the main suggestion is to always try and solve it with
coroutineScope
first. In this case, it seems to me that:
Copy code
suspend fun runTask(): Unit = coroutineScope {
    val task = launch { SomeDaemon(this).run() }

    // wait for some condition

    task.cancel()
}
Would most likely suffice. I'm sure your actual usecase is more complex, and I would love to look at an example where solving it with
coroutineScope
seems less feasible. Because I'm giving talks on this topic and would love more feedback :)
c
Correct, I do think
launch
-then-
cancel
works for my use-case. I'm not sure why I didn't think of it 🤔
How do you get a reference to the daemon within the condition? I could use
lateinit var
but I don't think that's safe.
y
I would still do
lateinit var
, but maybe with a
CoroutineStart.UNDISPATCHED
or whatever it's called (which ensures the coroutine runs immediately)
c
Copy code
suspend fun runTask(): Unit = coroutineScope {
    val daemon = CompletableDeferredDaemon()
    val daemonJob = launch {
        SomeDaemon(this)
            .also { daemon.complete(it) }
            .run()
    }

    // wait for some condition
    … daemon.await().whatever(…) …

    daemonJob.cancel()
}
Is it a good idea to use
UNDISPATCHED
in the
launch
when the daemon gets its context from the launch? The daemon itself shouldn't be
UNDISPATCHED
y
As I understand, it's a CoroutineStart, not a context
c
Oh, true
Welp, it's not a performance-sensitive area of the application (this code runs only once, at the start of the test suite) so I'll keep the explicit CompletableDeferred, that seems less likely to cause problems in future refactors
w
The CompletableDeferred or the UNDISPATCHED solutions indeed seems legit to me. With the caveat that if you use UNDISPATCHED, you have an implicit contract that you rely on suspension mechanisms that requires rather advanced understanding of your colleagues. So I agree with your "that is more likely to cause problems in future refactors" If I go idealistic again I'd be as explicit as possible about there being mutable shared state. But if we start reworking
SomeDaemon
, we're opening another can of worms :)
Copy code
suspend fun runTask(): Unit = coroutineScope {
    val deamonState = MutableStateFlow<SomeDeamonState>(SomeDeamonState.Uninitialized)
    val daemonJob = launch {
        SomeDaemon(this, deamonState).run() // Now we don't "leak" SomeDeamon from here, but we explicitly share mutable state (also not always optimal ofc)
    }

    // wait for some condition checking deamonState
    
    daemonJob.cancel()
}
c
In my particular case, the daemon is a
SelectorManager
from Ktor Sockets, which is a kind of socket factory, so I do need an instance to it directly, but indeed a flow of some more specific value would be a better solution if applicable
If you're curious KTOR-9683 Sockets: cancelling a SelectorManager job's doesn't close it properly
😯 1
🫠 1