0

In Dagger 2, Is putting All ViewModels inside AppComponent is the right place.

Because I check this android google sample, All ViewModel scoped in the app component but I think the view model should be in it is view (Activity, Fragment) scope/subcomponent?

something like this:

@ContributesAndroidInjector(modules = [LoginActivityModule::class])
abstract fun contributeLoginActivity() : LoginActivity

-

@Module
abstract class LoginActivityModule {

    @Binds
    @IntoMap
    @ViewModelKey(LoginViewModel::class)
    abstract fun bindLoginViewModel(viewModel: LoginViewModel): ViewModel
}

To avoid memory-leak

I need explanation.

Nawaf Abdu
  • 615
  • 1
  • 7
  • 13
  • The sample you linked has the viewmodel in the [subcomponent of the fragments](https://github.com/android/architecture-samples/blob/dev-dagger/app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/di/TaskDetailComponent.kt#L6). – denvercoder9 May 02 '20 at 20:55
  • @sonnet I edit the link (sorry) it was different branch – Nawaf Abdu May 02 '20 at 21:08
  • 1
    It doesn't matter where the viewmodel @binds is defined. The viewmodel is [scoped to the fragment/activity](https://github.com/android/architecture-samples/blob/dagger-android/app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailFragment.kt#L47-L50). And the viewmodelfactory is [scoped to the subcomponent of the fragments](https://github.com/android/architecture-samples/blob/dagger-android/app/src/main/java/com/example/android/architecture/blueprints/todoapp/di/TaskDetailModule.kt#L33-L36). You can look into the generated DaggerAppComponent java file. – denvercoder9 May 02 '20 at 21:20
  • @sonnet Ahaa, Ok in case of Provides (of course not view model, other type), still doesn't matter? – Nawaf Abdu May 02 '20 at 22:43
  • Depends on whether you have applied a scope on the provides func or is unscoped. If it's unscoped then yeah, doesn't matter. But if you have a custom scope on the provides func, then it can only be used in the component with the same scope. https://stackoverflow.com/questions/53791779/customscope-may-not-reference-bindings-with-different-scopes – denvercoder9 May 02 '20 at 23:02

0 Answers0