This message was deleted.
# android
s
This message was deleted.
s
Just make a
suspend
function in repository and call it from the view model with the
viewModelScope
when it's created.
Also, #coroutines
s
If I use it in the viewModelScope then fetching will be tied to the UI. Repository will have no role at all.
s
Repository's role is to separate the data processing logic from the view model. The fetching should still be connected to a lifecycle. You can scope your view model to a nav graph (if you're using the navigation component) to persist the data between several screens
There's really no scope available for a repository. You can use GlobalScope but it's not a good idea
b
GlobalScope can often be helpful if you want your repository to outlast the lifecycle. For example, I have a request that creates a business entity on a server and regardless of orientation changes or navigation, I want this request to finish. (I do the same thing for loading data into cache.)
viewModelScope
is mostly to make sure that we don't send updates to non-existent activities. The real question is why or when you would want to cancel a request.
a
Generally when you use that pattern it's easier to manage if you give the repository a scope to use at construction time instead of GlobalScope. Launching coroutines in a constructor is something to be skeptical of, however, it can grow into code that is harder to test and reason about.
d
If the work the
repository
is doing needs to
independent
of the UI, then we can use
GlobalScope
, else it should have
suspend
function called from within the
viewModelScope
as @Se7eN said.
s
@droid If I am not wrong a suspend function if called from a
viewModelScope
will deliver the results in the
ViewModel
itself. Is that correct? That means the suspend function in the repository mostly act like a common method which can be called from different `ViewModel`s wherever the data would be needed.
d
Yes, that is correct. If the repository is a shared repository, then the functions within it can be called from within the scope of the sharing ViewModels.