Skip to content Skip to sidebar Skip to footer

Create Viewmodel With Application

I am trying to set data onto the ViewModel in a file in which I do not wish to hold any activity references. Class A -> set data onto the LiveData in ViewModel Has an Applicatio

Solution 1:

You can use AndroidViewModel, it is attached with application lifecycle.

An example:

publicclassProductViewModelextendsAndroidViewModel {


    privatefinal LiveData<ProductEntity> mObservableProduct;


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


    privatefinalint mProductId;


    privatefinal LiveData<List<CommentEntity>> mObservableComments;


    publicProductViewModel(@NonNull Application application, DataRepository repository,

            finalint 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;

    }


    publicvoidsetProduct(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.

*/

    publicstaticclassFactoryextendsViewModelProvider.NewInstanceFactory {


        @NonNull

        privatefinal Application mApplication;


        privatefinalint mProductId;


        privatefinal DataRepository mRepository;


        publicFactory(@NonNull Application application, int productId) {

            mApplication = application;

            mProductId = productId;

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

        }


        @Override

        public <T extendsViewModel> T create(Class<T> modelClass) {

            //noinspection unchecked

            return (T) newProductViewModel(mApplication, mRepository, mProductId);

        }

    }

}

Solution 2:

ViewModels are strongly tied to Activity's and Fragment's lifecycle so you cannot use them with application context and need to use Activity's and Fragment's context.

If you want to share data between fragments you can use getActivity() to get the same ViewModel which will hold your data and will survive as long as your Activity is in scope.

Post a Comment for "Create Viewmodel With Application"