Is there a way to access the Fragment args when us...
# dagger
t
Is there a way to access the Fragment args when using Hilt? I tried something like this:
Copy code
@InstallIn(FragmentComponent::class)
@Module
object MyFragmentModule {

    @Provides
    @FragmentScope
    internal fun providesViewModel(
        fragment: MyFragment,
        anotherDependency: Dependency
    ) = MyViewModel(
        fragment.requireArguments().getString("argument"),
        anotherDependency
    )
}

@AndroidEntryPoint
class MyFragment : Fragment() {
    // ...
}
However, this does not appear to work as it shows the following error when building:
Copy code
error: [Dagger/MissingBinding] com.myapp.MyFragment cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
Am I doing something wrong? This worked fine without Hilt when using Dagger Android.
a
Have you tried replacing
MyFragment
with a mere
Fragment
?
Yep just confirmed, a mere
Fragment
should work.
t
That works but it would be much better if I can just access MyFragment so I only need to retrieve the fragment args once (in MyFragment onCreate)
a
Then I'm afraid that you'll have to create a custom component for that and do your own
@BindsInstance
for your custom Fragment type. https://dagger.dev/hilt/custom-components
t
In that case it’s probably easier to move the args retrieval to the Dagger module. Thanks for the help.
a
or perhaps you can add a provisioning method from a
Fragment
to your
MyFragment
so you can do
Copy code
@Binds
fun bindsMyFragment(f: Fragment): MyFragment
But haven't tried that myself so not sure if it will work.
t
Ok, I’ll look into it, thanks!
👍 1
This works as well and looks like the easiest way:
Copy code
@Provides
@FragmentScope
internal fun providesViewModel(
    fragment: Fragment,
    anotherDependency: Dependency
) = MyViewModel(
    (fragment as MyFragment).myArgument,
    anotherDependency
)
a
Yeah that would absolutely work
j
you are doing that provides +
@ViewModelInject
?
t
No, I cannot use
@ViewModelInject
as I need to pass Fragment args to the view model.
👍 1