Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide Activity instance with Hilt

How can I translate something like this:

@Module
abstract class BaseActivityModule<A : AppCompatActivity> {
    @Binds
    abstract fun provideActivity(activity: A): AppCompatActivity

    companion object {
        @Provides
        @ActivityContext
        fun provideContext(activity: AppCompatActivity): Context = activity
    }
}

@Module
abstract class SomeActivityModule : BaseActivityModule<SomeActivity>()

So it can be used latter like:

@ActivityScope
class UtilsClass @Inject constructor(
    private val activity: AppCompatActivity,
    ...
){...}

I've migrated a playground project from dagger to hilt and it went super smooth, but I've stumbled across this use-case. I've changed the code so I wont be needing that instance any more but the curiosity remains.

Is it even possible now that we don't need this kind of setup:

@ActivityScope
@ContributesAndroidInjector(modules = [SomeActivityModule::class])
abstract fun someActivity(): SomeActivity
like image 860
GuilhE Avatar asked Feb 03 '23 15:02

GuilhE


2 Answers

i didn't try this code yet, if its not working please CMiMW,
according to documentation here, you can use predefined qualifers for Application Context and activity context.

your code may look like this

@ActivityScoped
class UtilsClass @Inject constructor(
@ActivityContext private val activity: Context,
... 
){
 ...
 val myActivity = if(context is MyActivity) context as MyActivity else throw ......  // check if its provided context was desired activity
 ...

}
like image 98
daya pangestu Avatar answered Feb 06 '23 15:02

daya pangestu


Yes, you can cast @ActivityContext to that of your activity, read on for more clarification.
@ActivityContext can be used to scope the bindings that require activity context. But similar to dagger scoping scheme, you can only scope in classes that are @ActivityScoped, i.e if you try @ActivityContext in a class and scope it with any other scope wider than @ActivityScoped, you will face compile time error

@dagger.hilt.android.qualifiers.ActivityContext android.content.Context cannot be provided without an @Provides-annotated method

Moreover, new bindings objects will instantiated every time any new activity is created.
refer https://developer.android.com/training/dependency-injection/hilt-android#component-scopes

like image 31
Raja Singla Avatar answered Feb 06 '23 16:02

Raja Singla