Share ViewModel between fragments that are in different Activity

后端 未结 6 1936
傲寒
傲寒 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:35

    I think we still get confused with the MVVM framework on Android. For another activity, do not get confused because it must necessarily be the same, why?

    This makes sense if it has the same logic (even if the logic could still be abstract in other useful classes), or if the view in the XML is almost identical.

    Let's take a quick example:

    I create a ViewModel called vmA, and an activity called A and I need the user's data, I will go to insert the repository in vmA of the User.

    Now, I need another activity that needs to read user data, I create another ViewModel called vmB and in it I will call the user repository. As described, the repository is always the same.

    Another way already suggested is to create N instances of the same ViewModel with the implementation of the Factory.

提交回复
热议问题