Skip to content

Rethink ViewModel scoping #313

Open
Open
@RBusarow

Description

@RBusarow

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions