How can I use lifecyclescope in a class which does...
# coroutines
v
How can I use lifecyclescope in a class which does not have any lifecycle, Passing the context is it a good approach ?
j
If the class really doesn't have any kind of lifecycle, it is usually nice to stick to suspending functions. You can start coroutines inside
coroutineScope { ... }
blocks so you make sure they all finish before returning from your method. And in that case, the caller is responsible for starting long-lived coroutines with whatever scope it has. Having a scope is only useful when you want to launch coroutines that outlive your function/method. What's your use case for launching long-lived coroutines in such a class? If you really have a compelling one, you can indeed pass a
CoroutineScope
to enable launching coroutines, but first make sure it makes sense for the use case. If the class has some sort of lifecycle, you can also create your own
CoroutineScope
and make sure to cancel it in whatever hook you have for the end of your class's lifecycle (e.g. a
close()
method).
👍 1
v
Coroutinescope will end as well when the job is done right ?
j
I'm not entirely sure of what you're asking about, so let me clarify. The
CoroutineScope
interface defines object that have their own lifecycle and you can use them to launch coroutines. When the scope is canceled, all child coroutines end. The opposite is not true. If a coroutine ends normally, it doesn't cancel the scope (however it does cancel the scope if it fails with an exception, unless you're using a
SupervisorScope
). The
coroutineScope
function on the other hand is a suspending function, and resumes when all child coroutines inside are done.
v
So basically I have a use case where I am using a top most CoroutineScope to launch a coroutine and I am trying to cancel the coroutine once the task is done but the use case does not have any lifecycle
j
I have trouble understanding what you mean. In general the coroutine is the task, so when the task is over, the coroutine as well. For instance:
Copy code
scope.launch {
    doSomethingSuspending()
}
Here
launch
starts a new coroutine in the given
scope
. When
doSomethingSuspending
is done, the coroutine started by
launch
is also done (no need to cancel it).
👍 1