https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

Paul Woitaschek

11/19/2019, 8:13 AM
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

tseisel

11/19/2019, 8:45 AM
Try with
withContext(myClassScope.coroutineContext)
. I'm not sure it is good practice, but this seems to have the behavior you want.
s

streetsofboston

11/19/2019, 12:27 PM
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

Paul Woitaschek

11/19/2019, 12:56 PM
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

streetsofboston

11/19/2019, 12:59 PM
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

Paul Woitaschek

11/19/2019, 3:02 PM
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

streetsofboston

11/19/2019, 3:26 PM
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

Paul Woitaschek

11/19/2019, 3:26 PM
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

streetsofboston

11/19/2019, 3:27 PM
Exactly…
I think a
CoroutineScope
is more than just its
coroutineContext
(even though that is its only interface val).
p

Paul Woitaschek

11/19/2019, 4:56 PM
Well the test shows that it certainly is more than the context
t

tseisel

11/19/2019, 8:05 PM
Some reminders on
CoroutineContext
VS
CoroutineScope
from Roman's blog post : https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055
3 Views