Share ViewModel between fragments that are in different Activity

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

I have a ViewModel named SharedViewModel:

public class SharedViewModel extends ViewModel {

    private final MutableLiveData selected = ne         


        
6条回答
  •  Happy的楠姐
    2020-12-08 05:36

    A little late but you can accomplish this using a shared ViewModelStore. Fragments and activities implement the ViewModelStoreOwner interface. In those cases fragments have a store per instance and activities save it in a static member (I guess so it can survive configuration changes).

    Getting back to the shared ViewModelStore, let say for example that you want it to be your Application instance. You need your application to implement ViewModelStoreOwner.

    class MyApp: Application(), ViewModelStoreOwner {
        private val appViewModelStore: ViewModelStore by lazy {
            ViewModelStore()
        }
    
        override fun getViewModelStore(): ViewModelStore {
            return appViewModelStore
        }
    }
    

    Then in the cases when you know that you need to share ViewModels between activity boundaries you do something like this.

    val viewModel = ViewModelProvider(myApp, viewModelFactory).get(CustomViewModel::class.java)
    

    So now it will use the Store defined in your app. That way you can share ViewModels.

    Very important. Because in this example the ViewModels live in your application instance they won't be destroyed when the fragment/activity that uses them gets destroyed. So you will have to link them to the lifecycle of the last fragment/activity that will use them, or manually destroy them.

提交回复
热议问题