Hello guys, i have a compose and a ViewModel, i wo...
# compose-android
b
Hello guys, i have a compose and a ViewModel, i would like to start a long running task using WorkManager, what would be the best way of doing it? I can start the workManager task inside the ViewModel, however in this case i would need to pass
context
to the ViewModel. From the documentation, viewModel should be context free. Also what happens when the compose is removed from the backstack but the task is still ongoing
s
Also what happens when the compose is removed from the backstack but the task is still ongoing
Do you need the task to stop working as soon as the UI is no longer there, in your case when you pop the backstack?
b
no it’s a long running task that need to go in background, so it lives beyond the screen. The solution is to use WorkManager, however i would need to
ApplicationContext
for that
f
you can create an abstraction on top of work manager, then you can inject the
context
in your abstraction. Ideally create an interface and an implementation, with the viewmodel depending on the interface only.
b
so far here is what i have
Copy code
class MyViewModel(app: Application): ViewModel {
   fun startTask() {
        WorkManager.getInstance(app).enqueue(workRequest)
    }
}
My question is to know if this is the best way of doing it ? My issue is regarding passing
ApplicationContext
to the
ViewModel
f
I personally do not use
context
in viewmodels, as it makes it more challenging to test them. That's why I suggested an abstraction that takes care of enqueuing the job, which you can also easily test by creating a fake that you provide to the viewmodel in your unit tests
👍 3
j
I recommend inject repositories or such, and those need workManager inject. That repo can be used in viewmodel as mentioned above. Avoid delegation of context as much as possible, easy cause memory leaks. If not using DI, could use ApplicationViewModel but would advise against it.