跟随Application生命周期的ViewModel

自定义一个Application并实现ViewModelStoreOwner接口
这个ViewModel可以供全局使用,无论多少Activity都可以共享这个ViewModel的数据,利用LiveData来全局同步数据

public abstract class BaseApplication extends Application implements ViewModelStoreOwner {
    public static Application application;
    static ViewModelStore viewModelStore;

    @Override
    public void onCreate() {
        super.onCreate();   
        application = this;
        viewModelStore = new ViewModelStore();//创建一个ViewModelStore
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        return viewModelStore;
    }
}

下面这个是自定义的ViewModel

public class DemoViewModel extends ViewModel {
    MutableLiveData userMutableLiveData;

    public LiveData getUsers() {
        if (userMutableLiveData == null) {
            userMutableLiveData = new MutableLiveData<>();
            userMutableLiveData.postValue(new User("", ""));
        }
        return userMutableLiveData;
    }

    public void setValue(User user) {
        userMutableLiveData.setValue(user);
    }
}

封装一个获取ViewModel的静态方法

public static  T getApplicationViewModel(Class cls) {
        return new ViewModelProvider((ViewModelStoreOwner) BaseApplication.application).get(cls);
    }
DemoViewModel viewmodel = ViewModelUtil.getApplicationViewModel(DemoViewModel.class);//获取我们刚才定义的DemoViewModel

接下来就可以使用这个ViewModel啦,这里需要用到这个具有生命周期的LiveData,如果不熟悉要提前了解一下,这里就不在叙述了.

你可能感兴趣的:(android,java,开发语言)