Skip to content

Hilt: Question, How to reuse a module and provide its bindings #2099

@MRezaNasirloo

Description

@MRezaNasirloo

We are trying out Hilt for our production project, we have a use case that I'm not sure how Hilt would handle it
This is our approach towards providing different bindidngs when resuing a module:

Note I simplified the code below our actual use case has lots of modules and using Qulifiers is not convenient

@Module
class WidgetListModule {

    @Provides
    @FragmentScope
    fun provideCategoryViewModelFactory(
        widgetListDataSource: WidgetListDataSource<*>, // Not provided anywhere, user should provide it
        compositeDisposable: CompositeDisposable,
        threads: Threads,
        alak: Alak,
    ): ViewModelProvider.Factory {
        return viewModelFactory {
            WidgetListViewModel(
                compositeDisposable = compositeDisposable,
                dataSource = widgetListDataSource,
                threads = threads,
                alak = alak,
            )
        }
    }
}

The module that includes this module

@Module(includes = [WidgetListModule::class])
class ManageModule {

    @Provides
    @FragmentScope
    fun provideWidgetListDataSource(
        api: ManagePostAPI
    ): WidgetListDataSource<*> {
        return WidgetListGetDataSource(api::getPage)
    }
}
@FragmentScope
@Subcomponent(modules = [ManageModule::class])
interface ManageFragmentInjector {
    fun inject(manageFragment: ManageFragment)
}

And we have cases that the injector being used to inject a field is determined at run time like this:

override fun inject() {
        if (args.source == "foo") {
            mainActivityComponent.fooFragmentInjector()
                .inject(this)
        } else {
            mainActivityComponent.barFragmentInjector()
                .inject(this)
        }
    }

So my question is how can I resuse a module and provide its dependencies with hilt?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions