Skip to content

Instantly share code, notes, and snippets.

View Nyame123's full-sized avatar

Nyame Bismark Nyame123

View GitHub Profile
class LoginActivity : AppCompatActivity() {
@Inject
lateinit var loginAnalyticsAdapter: LoginAnalyticsAdapter
override fun onCreate(savedInstanceState: Bundle?) {
DaggerLoginComponent.builder()
.context(this)
.appDependencies(
EntryPointAccessors.fromApplication(
// LoginAnalyticsAdapter.kt - File in the login module.
class LoginAnalyticsAdapter @Inject constructor(
@AuthInterceptorOkHttpClient okHttpClient: OkHttpClient
) { ... }
@Component(dependencies = [LoginModuleDependencies::class])
interface LoginComponent {
fun inject(activity: LoginActivity)
@Component.Builder
interface Builder {
fun context(@BindsInstance context: Context): Builder
fun appDependencies(loginModuleDependencies: LoginModuleDependencies): Builder
fun build(): LoginComponent
// LoginModuleDependencies.kt - File in the app module.
@EntryPoint
@InstallIn(SingletonComponent::class)
interface LoginModuleDependencies {
@AuthInterceptorOkHttpClient
fun okHttpClient(): OkHttpClient
}
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
val viewModel: MainActivityViewModel by viewModels()
…………
}
@HiltViewModel
class MainActivityViewModel @Inject constructor(private val appDatabase: AppDatabase): ViewModel(){
fun getDatabase(): List<Readings?>? {
return appDatabase.readingDao()!!.filterReadings("%%")
}
}
class ExampleContentProvider: ContentProvider() {
...
override fun query(...): Cursor {
val appContext = context?.applicationContext ?: throw IllegalStateException()
val hiltEntryPoint =
EntryPointAccessors.fromApplication(appContext, ExampleContentProviderEntryPoint::class.java)
val analyticsService = hiltEntryPoint.analyticsService()
...
class ExampleContentProvider : ContentProvider() {
@EntryPoint
@InstallIn(SingletonComponent::class)
interface ExampleContentProviderEntryPoint {
fun analyticsService(): AnalyticsService
}
...
}
@ActivityScoped
class AnalyticsAdapter @Inject constructor(
private val service: AnalyticsService
) { ... }
Android class ------------------ Components ------------------------------------ Scope
Application---- SingletonComponent -------------------------- @Singleton
Activity ---ActivityRetainedComponents -------- @ActivityRetainedScoped
ViewModel ------ ViewModelComponents -------- @ViewModelScoped
Activity ----- ActivityComponents ------------------ @ActivityScoped
Fragment ---- FragmentComponents ------- @FragmentScoped
View --------- ViewComponents ------------------ @ViewScoped
View annotated @WithFragmentBindings -- ViewWithFragmentComponents -- @ViewScoped
Service --------- ServiceComponent ------------ @ServiceScoped