Skip to content

Instantly share code, notes, and snippets.

@ftabashir
Forked from marcellogalhardo/ActivityScope.kt
Created May 15, 2020 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftabashir/727ff803ace48b5e200ff31d6c260f91 to your computer and use it in GitHub Desktop.
Save ftabashir/727ff803ace48b5e200ff31d6c260f91 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