Share ViewModel between fragments that are in different Activity

后端 未结 6 1943
傲寒
傲寒 2020-12-08 05:12

I have a ViewModel named SharedViewModel:

public class SharedViewModel extends ViewModel {

    private final MutableLiveData selected = ne         


        
6条回答
  •  天命终不由人
    2020-12-08 05:50

    Here's a link

    Hope it helps you. O(∩_∩)O~

    In addition:

    1) The inspiration for the code came from smart pointer in c++.

    2) It will be auto cleared when no activities or fragments references ShareViewModel. The ShareViewModel # onShareCleared() function will be called at the same time! You don't need to destroy them manually!

    3) If you use dagger2 to inject the ViewModelFactory for share the viewmodel
    between two activities (maybe three), Here's sample

提交回复
热议问题