Search code examples
android-jetpackandroid-workmanagerdagger-hilt

how do I access ViewModel inside Work Manager


I'm trying to access ViewModel using hilt inside the worker class which I created but unable to do so, can anyone help please?


Solution

  • You should not try do such a thing in no way. They have totally different lifecycle and one is UI related - the other is not. You should create some other object, like a Singleton, and use it to share the data between the ViewModel and the Work. You can pull the data or use Observer pattern. VM has onCleared method so you can unregister there if you use Observer and observe the data from the VM in the Singleton.