gpt4 book ai didi

android - 使用应用程序创建 ViewModel

转载 作者:行者123 更新时间:2023-12-04 02:50:32 24 4
gpt4 key购买 nike

我正在尝试将数据设置到我不想在其中保存任何 Activity 引用的文件中的 ViewModel。

A 类 -> 将数据设置到 ViewModel 中的 LiveData 上
具有应用程序类引用但不包含 Activity 或 fragment

B 类 -> 从 ViewModel 中的 LiveData 读取数据
有对 Activity 的引用。

类 B 可以随着 Activity 的配置更改而被销毁和重新创建。
A 类在内存中持久存在并不断将数据设置到 LiveData

问题:ViewModelProviders.of(activity or fragment).get()
ViewProviders 需要 Activity 或 fragment 实例。

最佳答案

您可以使用 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);

        }

    }

}

关于android - 使用应用程序创建 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55307761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com