I’d like to create a Unit returning suspend functi...
# coroutines
j
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?
Copy code
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
Why do you need to launch it? why can't you simply do
Copy code
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
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
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
Yes, this was more or less the intended behavior.