Skip to content

Instantly share code, notes, and snippets.

@IlyaGulya
Created May 14, 2025 12:07
Show Gist options
  • Save IlyaGulya/f24978f1de29d8eb6d4283bc3df362d0 to your computer and use it in GitHub Desktop.
Save IlyaGulya/f24978f1de29d8eb6d4283bc3df362d0 to your computer and use it in GitHub Desktop.
import dagger.Component
import javax.inject.Inject
import javax.inject.Singleton
// ===== Shared Singleton =====
@Singleton
class SharedService @Inject constructor() {
val id = System.identityHashCode(this)
}
// ===== Feature One =====
class FeatureOne {
@Inject
lateinit var sharedService: SharedService
fun printId() = println("FeatureOne sees: ${sharedService.id}")
}
// ===== Feature Two =====
class FeatureTwo {
@Inject
lateinit var sharedService: SharedService
fun printId() = println("FeatureTwo sees: ${sharedService.id}")
}
// ===== Shared Component =====
@Singleton
@Component
interface SharedComponent {
fun sharedService(): SharedService
}
// ===== Feature One Component (зависит от SharedComponent) =====
@Component(dependencies = [SharedComponent::class])
interface FeatureOneComponent {
fun inject(target: FeatureOne)
}
// ===== Feature Two Component (зависит от SharedComponent) =====
@Component(dependencies = [SharedComponent::class])
interface FeatureTwoComponent {
fun inject(target: FeatureTwo)
}
// ===== MAIN =====
fun main() {
val sharedComponent = DaggerSharedComponent.create()
val featureOneComponent = DaggerFeatureOneComponent.builder()
.sharedComponent(sharedComponent)
.build()
val featureTwoComponent = DaggerFeatureTwoComponent.builder()
.sharedComponent(sharedComponent)
.build()
val featureOne = FeatureOne()
val featureTwo = FeatureTwo()
featureOneComponent.inject(featureOne)
featureTwoComponent.inject(featureTwo)
featureOne.printId()
featureTwo.printId()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment