Skip to content

Instantly share code, notes, and snippets.

@rakshitsoni02
Last active October 18, 2023 11:33
Show Gist options
  • Save rakshitsoni02/1926be483cc0572da5093fdf7efda47e to your computer and use it in GitHub Desktop.
Save rakshitsoni02/1926be483cc0572da5093fdf7efda47e to your computer and use it in GitHub Desktop.
Dagger Assisted Injection example Android
class MenuItemSearchBehavior
@AssistedInject internal constructor(
@Assisted private val hint: String,
@Assisted private val activityProvider: () -> Activity,
@Assisted onMenuCreated: ((menu: Menu) -> Unit)?,
analytics: IMenuAnalytics
) : MenuBehavior(
menuRes = R.menu.menu_search,
R.id.action_search to { item -> analytics.trackMenuItemClicked(item) },
onMenuCreated = onMenuCreated
) {
....
@AssistedFactory
internal interface InternalFactory {
fun create(
activityProvider: () -> Activity,
hint: String,
onMenuCreated: ((menu: Menu) -> Unit)? = null,
): MenuItemSearchBehavior
}
class Factory @Inject internal constructor(private val internal: InternalFactory) {
fun create(
activity: Activity,
hint: String,
onMenuCreated: ((menu: Menu) -> Unit)? = null,
) = internal.create(
activityProvider = { activity },
hint = hint,
onMenuCreated = onMenuCreated
)
fun create(
fragment: Fragment,
hint: String,
onMenuCreated: ((menu: Menu) -> Unit)? = null,
) = internal.create(
activityProvider = { fragment.requireActivity() },
hint = hint,
onMenuCreated = onMenuCreated
)
}
}
ProductsFragment {
@Inject
lateinit var menuBehaviorFactory: MenuItemSearchBehavior.Factory
...
init {
InjectorProvider.requireAccountComponent().inject(this)
val hint = translateFromKey(com.cmcmarkets.translations.R.string.key_search_products)
addBehavior(
menuBehaviorFactory.create(
fragment = this,
hint = hint,
)
)
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment