How can I cancel something using another scope? I...
# coroutines
p
How can I cancel something using another scope? I have a class that has it's own lifecycle scope. Now when someone calls a suspend funtion on that class I want that function to get cancelled when the scope of the class is cancelled.
t
Try with
withContext(myClassScope.coroutineContext)
. I'm not sure it is good practice, but this seems to have the behavior you want.
s
I wrote a blurb about how to manage lifecycles and CoroutineScopes, including the situation you describe (one object with one lifecycle calling another object with a different lifecycle): “How can we use CoroutineScopes in Kotlin?” by Anton Spaans https://link.medium.com/duBgcEy6J1
p
But isn't what you describe the other way round? I need to cancel it when the first of the two scopes gets cancelled
s
I think you'll find that at the end of my article:
... Let’s flip it around. What happens if that other CoroutineScope finishes, gets canceled? What would happen to the calling CoroutineScope? ...
...
... the calling Coroutine will be canceled, but the CoroutineScope in which it runs remains active ...
p
Ah right
Actually kotlin complains and suggests to replace your async - await with exactly what @tseisel wrote
Ooh and it seems that the inspection is wrong
s
When you do
scope.async { … }.await()
or just where the
scope
is the same one as the calling scope or do
async { … }.await()
, using
withContext
makes sense and the linter suggests that. Using
withContext
to change scope seems wrong to me…. it probably works, but for some reason, it ‘looks’ wrong…
p
Nope it doesnt work for some reason, the inspection is wrong
The inspetion says we should replace the async-await so it looks like in the secon file. But it's a completely different behavior
@elizarov Do you know this is already reported?
s
Exactly…
I think a
CoroutineScope
is more than just its
coroutineContext
(even though that is its only interface val).
p
Well the test shows that it certainly is more than the context
t
Some reminders on
CoroutineContext
VS
CoroutineScope
from Roman's blog post : https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055