Skip to content

Marchuck/AssistedInjectAndroidWithAndroidPermisssions

Repository files navigation

AssistedInject on Android example

demonstration of assisted inject on Android.

The problem

Usually on Dagger 2 on Android, dependencies have application scope.

They can be treated as singletons, because Application instance is created once.

Sometimes we need some dependencies which need Android framework components (Activity / Fragment) in order to be constructed.

In this case we can create @ActivityScope / ActivityModule / @SubComponent stuff in order to achieve that.

This is a lot of code to write.

We can workaround this easily with nullable properties which are set after injection

class MyViewModel @Inject constructor(
    val dependency1: Dependency1,
    ..., 
    val dependencyN: DependencyN
) {

var other: ActivtyRelatedDependency? = null 

}

class MyActivity : Activity{

   fun onCreate(...){
    //viewModel could be application scoped(sth like singleton),
    // long-lived on ViewModelProviders map or could be instantiated fresh each time
    injectedViewModel = ...  
    injectedViewModel.other = ActivityRelatedDependency(MyActivity.this)
   }
   
}

with assisted inject we can just tell Dagger: "hey! create a factory for this particular viewmodel with following parameters"

class MyViewModel @AssistedInject constructor(
    val dependency1: Dependency1,
    ..., 
    val dependencyN: DependencyN, 
    @Assisted val other: ActivityRelatedDependency 
) {

    @AssistedInject.Factory
    interface Factory {
        fun create(other: ActivityRelatedDependency): MyViewModel
    }
}

class MyActivity : Activity{

   fun onCreate(...){
    
    //myViewModelFactory is generated by dagger  
    val shortLivedDependency = ActivityRelatedDependency(MyActivity.this)
    injectedViewModel = appComponent.myViewModelFactory.create(shortLivedDependency)
   }
   
}

I am not certain about that solution, PRs and other tips / suggestions are welcome.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages