Skip to content

Dagger ‐ Scoping using module

Devrath edited this page Oct 8, 2023 · 11 revisions

Observations

Output

Code

Scopes

ActivityScope.kt

@Scope
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope

Implementations

AnalyticsService.kt

class AnalyticsService {
    fun trackEvent(action:String){
        PrintUtils.printLog("Analytics service has tracked your action:-> $action")
    }
}

ImageProcessingService.kt

class ImageProcessingService {
    fun initiateImageProcessing(){
        PrintUtils.printLog("Image processing is initiated")
    }
}

Modules

AnalyticsServiceModule.kt

@Module
@DisableInstallInCheck
class AnalyticsServiceModule {
    @Singleton
    @Provides
    fun provideAnalyticsService() : AnalyticsService {
        return AnalyticsService()
    }
}

ImageProcessingServiceModule.kt

@Module
@DisableInstallInCheck
class ImageProcessingServiceModule {
    @ActivityScope
    @Provides
    fun provideImageProcessingService() : ImageProcessingService {
        return ImageProcessingService();
    }
}

Components

ApplicationComponent.kt

@Singleton
@Component(modules = [AnalyticsServiceModule::class])
interface ApplicationComponent {
    fun provideAnalytics() : AnalyticsService
}

ActivityComponent.kt

@ActivityScope
@Component(dependencies = [ApplicationComponent::class], modules = [ImageProcessingServiceModule::class])
interface ActivityComponent {

    fun provideAnalytics() : AnalyticsService
    fun provideImageProcessingService() : ImageProcessingService

}

Application

Activity

Clone this wiki locally