I'm creating a lifecycle aware class (that will be injected in the activity). It takes two params - event bus and lifecycle owner. In that case can I bind activity to the lifecycleowner?
My lifecycle aware class:
class Bus @Inject constructor(
private val eventBus: EventBus,
private val lifecycleOwner: LifecycleOwner) : LifecycleObserver { ... }
The binding in my module:
@Binds
abstract fun bindLifecycle(activity: SampleActivity): LifecycleOwner
And then I'm injecting the Bus in ActivityX as usual:
@Inject
lateinit var bus: Bus
I'm getting the following error: ActivityX cannot be provided without an @Inject constructor or an @Provides-annotated method.
So my question: is my approach correct OR it's not possible, since activities DON'T support constructor injection?
@Binds
annotation "ties" a dependency that is already provided by Dagger
to some other type.
By using:
@Inject
lateinit var bus: Bus
you're not making SampleActivity
a Dagger dependency (so it is not provided by Dagger
). It only uses dependencies provided by Dagger
so it cannot be used with @Binds
annotation.
You should have an ActivityModule
that can expose a LifecycleOwner
as a dependency:
@Module
class ActivityModule(private val activity: AppCompatActivity) {
@Provides
fun provideLifecycleOwner(): LifecycleOwner {
return activity
}
}
( remember that the class that will use a LifecycleOwner
must share the scope with the component that uses ActivityModule
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.