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

Slackbot

09/15/2020, 7:42 AM
This message was deleted.
s

Se7eN

09/15/2020, 9:59 AM
Just make a
suspend
function in repository and call it from the view model with the
viewModelScope
when it's created.
Also, #coroutines
s

Sudhir Singh Khanger

09/15/2020, 10:47 AM
If I use it in the viewModelScope then fetching will be tied to the UI. Repository will have no role at all.
s

Se7eN

09/15/2020, 11:24 AM
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

bsimmons

09/15/2020, 11:37 AM
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

Adam Powell

09/15/2020, 2:14 PM
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

droid

09/15/2020, 2:19 PM
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

Sudhir Singh Khanger

09/16/2020, 5:05 AM
@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

droid

09/16/2020, 12:18 PM
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.