Skip to content

Instantly share code, notes, and snippets.

@marcellogalhardo
Last active January 20, 2021 10:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marcellogalhardo/485b289702348c3f8e8b22bd5c6a1440 to your computer and use it in GitHub Desktop.
Save marcellogalhardo/485b289702348c3f8e8b22bd5c6a1440 to your computer and use it in GitHub Desktop.
Scoping Dagger Components with ViewModels
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope
dependencies {
//other dependencies...
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0'
implementation 'com.google.dagger:dagger:2.24'
kapt 'com.google.dagger:dagger-compiler:2.24'
}
abstract class ScopedComponent : ViewModel()
@MainThread
inline fun <reified C : ScopedComponent> AppCompatActivity.components(
noinline ownerProducer: () -> ViewModelStoreOwner = { this },
noinline factory: () -> C
) = viewModels<C> { viewModelFactoryOf { factory() } }
@MainThread
inline fun <reified VM : ViewModel> viewModelFactoryOf(
noinline factory: () -> VM
) = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <VM : ViewModel?> create(modelClass: Class<VM>): VM {
return factory() as VM
}
}
class MainActivity: AppCompatActivity() {
@Inject
lateinit var mainPresenter: MainPresenter
private val component: MainComponent by components {
DaggerMainComponent.create()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
component.inject(this)
mainPresenter.counter++
findViewById<TextView>(R.id.message).text = mainPresenter.counter.toString()
}
}
@ActivityScope
@Component
abstract class MainComponent : ScopedComponent() {
abstract fun inject(target: MainActivity)
}
@ActivityScope
class MainPresenter @Inject constructor(
val mainRepository: MainRepository
) {
var counter: Int = 0
}
@Reusable
class MainRepository @Inject constructor()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment