How to provide arguments like this `Callback` in ...
# dagger
k
How to provide arguments like this
Callback
in Fragment using HILT
Copy code
class PostAdapter @Inject constructor(
    @ApplicationContext private val context: Context,
    private val callback: Callback //HOW THIS CAN BE PROVIDED FROM FRAGMENT
) : ListAdapter<Post, PostAdapter.Holder>(DIFF) {

  /.../

   interface Callback {
        fun onClick(post: Post)
    }

}
r
Depends on what that callback does
Do you want your
Fragment
to implement this
Callback
?
j
Why do you need the context? You can get the context from the view
👍 1
k
@Rafal yes i want to implement it in fragment
@Javier yes, i can skip context but Callback should be implemented by fragment and @Inject using Hilt
r
then the only thing I can think of is to make a method that could provide an
Optional<Callback>
in the fragment scoped module
Copy code
@Provides
fun provideCallback(fragment: Fragment): Optional<Callback> = if(fragment is Callback) Optional.of(fragment) else Optional.empty()
k
@Rafal looks like it would work
but this maybe too much for this case
i am thinking to create Adapter instance manually in fragment
r
well, with your constructor arguments this sounds like a better option
j
I don't think you should use DI for this btw
r
+1 to above. You should not use DI for callback.
d
@Rafal You don't need to wrap fragment with Optional. You can just bind fragment to Callback type.
Copy code
@Binds
fun bindCallback(fragment: Fragment): Callback
r
how does Dagger will know if the fragment actually implements this
Callback
d
From this binding
This the common use of
@Binds
k
@dawidhyzy looks cool, so i don’t have to provide any implementation ?
because @Binds is going to be
abstract
if i’m not wrong
and it would be better to add parameter fragment more specific like @Rafal You don't need to wrap fragment with Optional. You can just bind fragment to Callback type ???
Copy code
@Binds
fun bindCallback(fragment: LoginFragment): Callback
r
It wont work with hilt because you cant bind concrete fragment instance
If you install your module inside the FragmentComponent you can only refference the
Fragment
class
You will get the error that you cant bind instance from class that doesnt implement given interface
You could do that in dagger-android