Solution to Deprecated method ViewModelProviders#of

As source code mentioned, the static method ViewModelProviders#of was deprecated.

     * @deprecated Use the 'by viewModels()' Kotlin property delegate or
     * {@link ViewModelProvider#ViewModelProvider(ViewModelStoreOwner)},
     * passing in the activity.
    public static ViewModelProvider of(@NonNull FragmentActivity activity) {
        return new ViewModelProvider(activity);

This solution is using ‘by viewModels()’ instead.

  1. Add lib fragment-ktx in dependencies
dependencies {
    implementation 'androidx.fragment:fragment-ktx:1.1.0'
  1. Define quizViewModel as follows:
    private val quizViewModel: QuizViewModel by viewModels()

This wasn’t showing for me. I looked into dependency versions.

If using

implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'

Then, the method is not deprecated. It was deprecated in

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha03

I tend to not use the alpha/beta/rc versions until it goes final. Thanks for the tip moving forward.

I wonder if by viewModels() will be moved in to the lifecycle-extensions dependency at some point. The by viewModels() solution is more elegant.

Thanks for the review. :grinning: