Android LiveData - how to reuse the same ViewModel on different activities?

后端 未结 3 1617
情歌与酒
情歌与酒 2020-12-14 15:13

Example ViewModel:

public class NameViewModel extends ViewModel {
    // Create a LiveData with a String
    private MutableLiveData mCurrentNa         


        
3条回答
  •  失恋的感觉
    2020-12-14 15:48

    When you call ViewModelProviders.of(this), you actually create/retain a ViewModelStore which is bound to this, so different Activities have different ViewModelStore and each ViewModelStore creates a different instance of a ViewModel using a given factory, so you can not have the same instance of a ViewModel in different ViewModelStores.

    But you can achieve this by passing a single instance of a custom ViewModel factory which acts as a singleton factory, so it will always pass the same instance of your ViewModel among different activities.

    For example:

    public class SingletonNameViewModelFactory extends ViewModelProvider.NewInstanceFactory {
    
    
        NameViewModel t;
    
        public SingletonNameViewModelFactory() {
          //  t = provideNameViewModelSomeHowUsingDependencyInjection
        }
    
        @Override
        public NameViewModel create(Class modelClass) {
            return t;
        }
    }
    

    So what you need is to make SingletonNameViewModelFactory singleton (e.g. using Dagger) and use it like this:

    mModel = ViewModelProviders.of(this,myFactory).get(NameViewModel.class);
    

    Note:

    Preserving ViewModels among different scopes is an anti-pattern. It's highly recommended to preserve your data-layer objects (e.g. make your DataSource or Repository singleton) and retain your data between different scopes (Activities).

    Read this article for details.

提交回复
热议问题