I just started using the architecture component of Android in my app, and I have a use case when:
- A fragment is an observer of
ViewModel
'sLiveData
(which comes from aRoom
request) - This fragment starts an activity at some point
- The activity needs to use the same data (as
LiveData
in the fragment) and update it - The user then returns to the fragment
I tried using the same ViewModel
class and adding the fragment and activity as observers, thinking that somehow updating from the activity will affect the fragment when returning to it, but it doesn't work.
The two ViewModel
s seem independent.
How can I force refresh the fragment data when returning from the activity (in onActivityResult
for example)?
Or is it possible to share the same ViewModel
between the fragment and activity? (though I doubt it since the ViewModel
is linked to the lifecycle of the observer)
Fragment
public void onAttach(@NonNull Context context) {
...
mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
mViewModel.getData().observe(this, new Observer<List<Data>>() {
@Override
public void onChanged(List<Data> data) {
mAdapter.setData(data);
}
});
}
// in an onClick method
startActivity(intent); // go to the Activity
Activity
protected void onCreate(Bundle savedInstanceState) {
...
mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
mViewModel.getData().observe(this, new Observer<List<Data>>() {
@Override
public void onChanged(List<Data> data) {
mPagerAdapter.setData(data);
}
});
}
Any help will be appreciated!
EDIT:
View Model
public class MyViewModel extends AndroidViewModel {
private Dao dao;
private ExecutorService executorService;
public MyViewModel (@NonNull Application application) {
super(application);
dao = AppDatabase.getInstance(application).getDao();
executorService = Executors.newSingleThreadExecutor();
}
public LiveData<Data> getData() {
return dao.getAllData();
}
// other methods to update and delete with executorService
}