使用应用程序创建ViewModel

时间:2019-03-22 21:05:22

标签: android android-livedata android-viewmodel

我试图将数据设置到我不希望保存任何活动引用的文件中的ViewModel上。

A类->将数据设置到ViewModel中的LiveData上 具有Application类引用,但不包含活动或片段

B类->从ViewModel中的LiveData读取数据 对该活动有参考。

B类可以随Activity的配置更改一起销毁并重新创建。 类A持久存储在内存中,并将设置数据保存到LiveData

问题:ViewModelProviders.of(活动或片段).get() ViewProvider需要活动或片段实例。

2 个答案:

答案 0 :(得分:0)

ViewModels与Activity和Fragment的生命周期紧密相关,因此您不能将它们与应用程序上下文一起使用,而需要使用Activity和Fragment的上下文。

如果要在片段之间共享数据,则可以使用getActivity()获取相同的ViewModel,该ViewModel将保存您的数据,并且只要您的Activity处于作用域内就可以生存。

答案 1 :(得分:-1)

您可以使用AndroidViewModel,它与应用程序生命周期相关。

一个例子:

public class ProductViewModel extends AndroidViewModel {


    private final LiveData<ProductEntity> mObservableProduct;


    public ObservableField<ProductEntity> product = new ObservableField<>();


    private final int mProductId;


    private final LiveData<List<CommentEntity>> mObservableComments;


    public ProductViewModel(@NonNull Application application, DataRepository repository,

            final int productId) {

        super(application);

        mProductId = productId;


        mObservableComments = repository.loadComments(mProductId);

        mObservableProduct = repository.loadProduct(mProductId);

    }


    /**

* Expose the LiveData Comments query so the UI can observe it.

*/

    public LiveData<List<CommentEntity>> getComments() {

        return mObservableComments;

    }


    public LiveData<ProductEntity> getObservableProduct() {

        return mObservableProduct;

    }


    public void setProduct(ProductEntity product) {

        this.product.set(product);

    }


    /**

* A creator is used to inject the product ID into the ViewModel

* <p>

* This creator is to showcase how to inject dependencies into ViewModels. It's not

* actually necessary in this case, as the product ID can be passed in a public method.

*/

    public static class Factory extends ViewModelProvider.NewInstanceFactory {


        @NonNull

        private final Application mApplication;


        private final int mProductId;


        private final DataRepository mRepository;


        public Factory(@NonNull Application application, int productId) {

            mApplication = application;

            mProductId = productId;

            mRepository = ((BasicApp) application).getRepository();

        }


        @Override

        public <T extends ViewModel> T create(Class<T> modelClass) {

            //noinspection unchecked

            return (T) new ProductViewModel(mApplication, mRepository, mProductId);

        }

    }

}