Search code examples
androidmvvmlifecycle

How to share the same ViewModel between Activity and Service when ViewModelProviders.of() is deprecated?


In new androidx.lifecycle:lifecycle-extensions:2.2.0 library, ViewModelProviders.of() is deprecated. It suggested that we should

 * @deprecated Use the 'by viewModels()' Kotlin property delegate or
 * {@link ViewModelProvider#ViewModelProvider(ViewModelStoreOwner)},
 * passing in the activity.

However, I want to share the same ViewModel instance between an activity and a service, I cannot use 'by viewModels()' delegation. Could anyone point out what is the correct way of doing this?

Thanks a lot


Solution

  • Just replace it, with

    In Activity:
    Kotlin: ViewModelProvider(this).get(CustomViewModel::class.java)
    Java: ViewModelProvider(this).get(CustomViewModel.class)

    In Service:
    create an instance of viewModel with keyword new inside service class

    these work for me :)