This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@DefineComponent(parent = ApplicationComponent::class) | |
internal interface UserComponent | |
@DefineComponent.Builder | |
internal interface UserComponentBuilder { | |
fun withUserId(@BindsInstance userId: Int): UserComponentBuilder | |
fun build(): UserComponent | |
} | |
@DefineComponent(parent = UserComponent::class) | |
internal interface ActivityUserComponent | |
@DefineComponent.Builder | |
internal interface ActivityUserComponentBuilder { | |
fun withActivity(@BindsInstance activity: Activity): ActivityUserComponentBuilder | |
fun build(): ActivityUserComponent | |
} | |
@EntryPoint | |
@InstallIn(UserComponent::class) | |
internal interface ActivityUserComponentBuilderEntryPoint { | |
fun activityUserComponentBuilder(): ActivityUserComponentBuilder | |
} | |
@EntryPoint | |
@InstallIn(ActivityUserComponent::class) | |
interface CalendarInjector { | |
fun inject(calendarActivity: CalendarActivity) | |
} | |
internal var currentUser: UserComponent? = null | |
internal fun createUserComponent(application: Application, userId: Int = 1) = | |
(application as CalendarApp).userComponentBuilder.withUserId(userId) | |
.build() | |
internal fun createActivityComponent(activity: Activity): ActivityUserComponent { | |
val userComponent: UserComponent = currentUser ?: createUserComponent(activity.application) | |
val buildEntryPoint = userComponent as ActivityUserComponentBuilderEntryPoint | |
return buildEntryPoint | |
.activityUserComponentBuilder() | |
.withActivity(activity) | |
.build() | |
} | |
@HiltAndroidApp | |
class CalendarApp : Application(){ | |
@Inject | |
internal lateinit var userComponentBuilder: UserComponentBuilder | |
} | |
@EntryPoint | |
@InstallIn(ActivityUserComponent::class) | |
interface CalendarInjector { | |
fun inject(calendarActivity: CalendarActivity) | |
} | |
private fun calendarInjector(calendarActivity: CalendarActivity) { | |
val activityComponent = createActivityComponent(calendarActivity) | |
EntryPoints.get(activityComponent, CalendarInjector::class.java).inject(calendarActivity) | |
} | |
class CalendarActivity : AppCompatActivity() { | |
@Inject | |
lateinit var userId: Integer | |
@Inject | |
lateinit var activity: Activity | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
calendarInjector(this) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment