Reputation: 641
my situation is that I am trying to get a list of strings List<String>
from my Room database and send it over to Retrofit to retrieve information.
I don't want to use LiveData because I would need to have a nested observer in the View to observe the data in the database and another to get the list of data from Retrofit.
I am trying to use coroutines but am unsure how to return data from the viewModelScope.launch function when it is finally done getting the values.
Upvotes: 0
Views: 204
Reputation: 83527
I don't want to use LiveData because I would need to have a nested observer in the View to observe the data in the database and another to get the list of data from Retrofit.
You can define your observers as top-level classes instead of nesting them. You can do this either as a private class in the same file as the class where they are used or as a public class in a separate file. This is a good solution if your concern is an overly complex, deeply-nested, long source file. It will allow you to more easily share code if necessary.
For example, if you have the following observer in your view:
final Observer<String> nameObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
nameTextView.setText(newName);
}
};
Then you create a named class:
class MyObserver extends Observer<String> {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
nameTextView.setText(newName);
}
}
and then in your view:
final Observer<String> nameObserver = new MyObserver();
If you insist on avoiding LiveData
, you can do what you want with a AsyncTask
or roll your own threaded implementation.
Upvotes: 1