|
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() |
|
} |