Share ViewModel across Fragments with Dagger Scopes in Single Activity App

I’m guessing that you’re talking about androidx.lifecycle.ViewModel which manages its own lifecycle and should not have any scope to allow for it to do just that. If you add your own scopes on top it’ll just end up with broken and/or confusing behavior.

As such you shouldn’t inject those ViewModels directly either but use the ViewModel factories and lookup methods, or—again—you’d end up with broken and/or confusing behavior since the ViewModel would behave differently to what all of its official documentation states. (You may write a bunch of boilerplate to move this process into modules, but ultimately you’d still need to let androidx manage the lifecycle)

If you don’t want to use androidx.lifecycle.ViewModel but want to get the same/similar behavior then you’d have to create your own scope in-between components. That scope should live shorter than the application, but longer than any single Activity instance to allow for those objects to be reused after configuration changes and so on.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top