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

Sudhir Singh Khanger

09/15/2020, 10:45 AM
Which Coroutine scope do I use in an Android MVVM Repository? I want to execute a Retrofit call when the repository is created and store its result in a MutableLiveData object within it. That way as long as the repository is not destroyed the use could navigate to the screen and the data would be available. It won't be downloaded over and over if I were to call the retrofit call in the viewModelScope.
g

gildor

09/15/2020, 11:11 AM
Just pass any scope with the same lifecycle Does it even can be destroyed? If not, so it essentially singleton, then you can use global scope
s

Sudhir Singh Khanger

09/15/2020, 11:20 AM
I can use viewModelScope but but then the network call will end up depending on the UI lifecycle. Network layer/repository will be a singleton. I was wondering if there are any caveats to using GlobalScope. But it does seem like that's the only option for asynchronous work in singleton objects that don't have a typical UI like life cycle.
f

flosch

09/15/2020, 11:28 AM
You can change the dispatcher that a coroutine is run on in a scope. Use
withContext(Dispatcher)
for coroutines,
flowOn(Dispatcher)
for Flow. In your use-case you would have a suspending function in your repo that runs on IO but is launched in the
viewmodelScope
r

Rechee Jozil

09/15/2020, 3:33 PM
so far, I've made repositories just have suspend functions. Maybe if I want to have some random side effect in the function I'll inject a global scope. But... You seem to want to have some caching mechanism? You sure you need Coroutines for that? Anyways for repository I'd use a global scope (not capital G global scope. In my apps I have my own global scope with my own context)
s

Sudhir Singh Khanger

09/16/2020, 5:07 AM
But... You seem to want to have some caching mechanism? You sure you need Coroutines for that?
I don't need Coroutine for caching. I need it for running a background task. The idea is that a suspend function downloads the data and then I keep it in a LiveData object in the Repository itself. As long as the repository is alive the user would always see the data. It can navigate out of the view and then come back and the data would be there. The API won't be called over and over every time the user visits the UI.
g

gildor

09/16/2020, 5:22 AM
so what is problem with it?
use any scope which matches lifecycle of this repository, repository may have any lifecycle depends on your use case
12 Views