Tangle icon indicating copy to clipboard operation
Tangle copied to clipboard

Rethink ViewModel scoping

Open RBusarow opened this issue 4 years ago • 0 comments

Currently, ViewModels have their own scope, and the parent is the application scope: image

There should really be an option to have something in between.

Hilt has an "activity retained" scope in between: image In a nearly-single-activity application, this allows us to use Activity as a sort of proxy for scoping. For instance, to implement a LoggedInScope, we can have different activities for logged-in vs not-logged-in workflows. However, this is coupling the framework to business logic.

The problem with ViewModels, particularly in Compose apps, is that a ViewModel can arguably be called an "entry point" into the Dagger graph. Even though a ViewModel will be constructor-injected, it's provided via the ViewModelProvider.Factory.

The existing design should be updated so that there's an Activity component in between, the same as with Hilt. However, it would be nice to provide an option for a different scope via the TangleScope annotation.

@TangleScope(UserScope::class) // optional
class UserViewModel @VMInject constructor( /* ... */ ) : ViewModel {
  // ...
}

Then in TangleViewModelFactory, we can check for a custom scope and use the corresponding component if necessary. If there is no custom scope defined, then the factory would just fall back to the default.

RBusarow avatar Sep 09 '21 00:09 RBusarow