简体   繁体   中英

Android: How can I use send data from Room to Retrofit without LiveData?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM