Share ViewModel between fragments that are in different Activity

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

    Well, I created a library for this purpose named Vita, You can share ViewModels between activities and even fragments with different host activity:

    val myViewModel = vita.with(VitaOwner.Multiple(this)).getViewModel()
    

    The created ViewModel in this way stay alive until its last LifeCycleOwner is destroyed.

    Also you can create ViewModels with application scope:

    val myViewModel = vita.with(VitaOwner.None).getViewModel()
    

    And this type of ViewModel will be cleared when user closes app

    Give it a try and kindly let me know your feedback: https://github.com/FarshadTahmasbi/Vita

提交回复
热议问题