0

In Dagger, You can inject your activity as View in Presenter, Please follow below example,

Splash Module

@Module
class SplashModule {
    @Provides
    fun provideXUseCase(
        xRepository: XRepository
    ) = XUseCase(xRepository)


    @Provides
    fun provideSplashPresenter(
        view: SplashView,
        xUseCase: XUseCase
    ): SplashPresenter = SplashPresenter(
        view,
        xUseCase
    )
}

View Module

@Module
abstract class ViewModule {
    @Binds
    abstract fun provideSplashView(activity: SplashActivity): SplashView
}

Activity Module

@Module
abstract class ActivitiesModule {
    @ContributesAndroidInjector(modules = [SplashModule::class, ViewModule::class])
    abstract fun bindSplashActivity(): SplashActivity
}

I tried to find how to do it in ToothPick, but could not find any official document or blog post!

Thanks

AndiGeeky
  • 11,266
  • 6
  • 50
  • 66

1 Answers1

1

Yes, you can do it in a very similar fashion.

You can have a module that binds the view interface to an InstanceProvider (which you can define as a lambda)

In the presenter you declare the View as @Inject and then call Toothpick.inject() as part of the initialization.

The only tricky part is to take care of the scope tree. When I did this I used an Application scope as well as an Activity scope and only declared the bind of the View at Activity level, then the presenter calls inject with the same scope and it all should work fine.

The Activity scope is needed so we override the InstanceProvider each time a new Activity is created (and the View has a new reference and I recall the old one was cached if the scope was the same)

I hope I explained it properly. It wasn't obvious how to do it, but once all the pieces are in place it makes sense.

shalafi
  • 3,926
  • 2
  • 23
  • 27