Hi. I have to clear db when exit fragment. I am cr...
# coroutines
k
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
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
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
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
I have a confusion. Will this coroutineScope leak if app closes?
m
if it doesn’t leak while the app is running, it will not leak when the app is closed.
k
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
Nope. Assuming that your coroutine will come to a stop eventually..
👍 1
k
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
It creates a new scope inside ViewModel
No one has talked about creating a scope in a ViewModel.