https://kotlinlang.org logo
Title
j

julioromano

06/25/2021, 8:51 AM
I’d like to create a Unit returning suspend function which launches another coroutine inside it and must not return until that coroutine has finished. Is this “pattern” a good way for implementing this?
suspend fun myFunction(myParam: String): Unit = myScope.launch {
	doSomethingElseSuspending()
	withContext(anotherContext) { doSomeOtherStuffInTheOtherContext(myParam) }
}.join()
The rationale is that the caller of
myFunction
should not care of what’s happening inside it, the caller merely calls a suspending function (
myFunction()
) that suspends until all work done inside it is done and then either throws or returns Unit.
b

bezrukov

06/25/2021, 9:10 AM
Why do you need to launch it? why can't you simply do
suspend fun myFunction(myParam: String) {
	doSomethingElseSuspending()
	withContext(anotherContext) { doSomeOtherStuffInTheOtherContext(myParam) }
}
In your case you don't preserve a caller's context - e.g. if outer scope is cancelled, cancellation won't be propagated to launched coroutine via join
j

julioromano

06/25/2021, 9:38 AM
if outer scope is cancelled, cancellation won’t be propagated to launched coroutine via join
That was the purpose: whatever
myFunction
does should keep on going if the the outer scope is cancelled. In addition
myScope
has a
SupervisorJob
and
CoroutineExceptionHandler
in it so that if anything inside
myFunction
throws the exception will be propagated via other means by the Handler.
j

Justin Tullgren

06/29/2021, 7:20 PM
cooperative cancellation is big promise of coroutines. Seems like this goes against it. Sounds more like you need to submit a task to some processor which returns a a token which can query the status of the job if needed or it can go away and the processor continues
j

julioromano

06/30/2021, 6:22 AM
Yes, this was more or less the intended behavior.