I have two Fragment
-s with RecyclerView
and LiveData
both. When I made some changes in second fragment, I need to update RecyclerView
in first fragment.
So after update second fragment I need to trigger onChange
method in first fragment.
Code from first fragment:
item_viewmodel.getAllCategoryModel().observe(getViewLifecycleOwner(), new Observer<List<Items>>() {
@Override
public void onChanged(List<Items> myLists) {
//Observer is already registered, but I need to call it manully from second fragment.
}
});
How can I do this?
CodePudding user response:
You can achieve this by using Shared viewmodel, create a instance of viewmodel in both the fragments and use accordingly, for more details visit this page link
CodePudding user response:
You should try use Transformations.switchMap() method, put that the first livedata depends of the second livedata by the method describe above
Here is an example class that holds a typed-in name of a user String (such as from an EditText) in a MutableLiveData and returns a LiveData containing a List of User objects for users that have that name. It populates that LiveData by requerying a repository-pattern object each time the typed name changes.
This ViewModel would permit the observing UI to update "live" as the user ID text changes.
class UserViewModel extends AndroidViewModel {
MutableLiveData<String> nameQueryLiveData = ...
LiveData<List<String>> getUsersWithNameLiveData() {
return Transformations.switchMap(
nameQueryLiveData,
name -> myDataSource.getUsersWithNameLiveData(name));
}
void setNameQuery(String name) {
this.nameQueryLiveData.setValue(name);
}
}
If you want more specific answer please post all code about your viewModel
CodePudding user response:
I assume best way would be to use by activityViewModels()
kotlin property delegate in fragments and share the host activity's Viewmodel
for cross fragment communication.
More about usage here