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

Khan

10/31/2019, 9:47 AM
Hi. I have to clear db when exit fragment. I am creating a coroutine to clear db table inside viewmodel onCleared. As you can see i am not using viewModelScope because my table will not be cleared and coroutine will be cancelled. Do you think its fine to use CoroutineScope here?
m

Martin Nordholts

10/31/2019, 11:38 AM
Add a scope to your
repository
by inheriting from
: CoroutineScope by MainScope()
, then you can
launch
from within your
repository
instead of from outside it
p

Paul Woitaschek

11/01/2019, 7:09 AM
I douldn't do that. You are exposing a buch of stuff then. For example you can close your repository now from the outside 😉
A repository is no CoroutineScope, a repository can have a CoroutineScope.
m

Martin Nordholts

11/01/2019, 7:19 AM
If that is of concern, then better to add a
private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
and use
coroutineScope.launch
Personally I have no problem with a repository being a scope though. Especially not in Kotlin where it is by delegation and does not put a limit on your inheritance hierachy.
k

Khan

11/01/2019, 9:23 AM
I have a confusion. Will this coroutineScope leak if app closes?
m

Martin Nordholts

11/01/2019, 9:25 AM
if it doesn’t leak while the app is running, it will not leak when the app is closed.
k

Khan

11/01/2019, 9:28 AM
So for example if i create a coroutine in repo and then i exit from screen & my coroutine is still running. Anything bad in that?
m

Martin Nordholts

11/01/2019, 9:34 AM
Nope. Assuming that your coroutine will come to a stop eventually..
👍 1
k

Khan

11/02/2019, 11:36 PM
It creates a new scope inside ViewModel and does not cancel itself, if it’s not finishing the job before the ViewModel gets cleared then the ViewModel can’t be garbage collected and a leak will occur. Is this a correct statement in the above context?
m

Martin Nordholts

11/03/2019, 10:31 AM
It creates a new scope inside ViewModel
No one has talked about creating a scope in a ViewModel.
3 Views