Last active
July 8, 2020 15:24
-
-
Save victorrattis/281168d9a91fd98d1c88b747b9854c02 to your computer and use it in GitHub Desktop.
Using HILT to Inject the presenter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component(modules = [AppModule::class]) | |
interface AppComponent { | |
fun plus(mainActivityModule: MainActivityModule): SugarLevelComponent | |
} | |
@Module | |
clsas AppModule { | |
/* ... */ | |
} | |
@Subcomponent(modules = [MainActivityModule::class]) | |
interface SugarLevelComponent { | |
fun inject(mainActivity: MainActivity) | |
} | |
@Module | |
class MainActivityModule constructor( | |
private val mainActivity: MainActivity | |
){ | |
@Provides fun providerPresenter(): MyPresenterInterface = MyPresenter(mainActivity) | |
} | |
// inject | |
class MainActivity : AppCompatActivity, MyView { | |
override fun onCreate(...) { | |
DaggerAppComponent | |
.builder() | |
.mainAppModule(AppModule(applicationContext)) | |
.build() | |
.plus(MainActivityModule(this)) | |
.inject(this) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@HiltAndroidApp | |
class MyApplication : Application() | |
interface MainContract { | |
interface View { | |
/* ... */ | |
} | |
interface Presenter { | |
/* ... */ | |
} | |
} | |
class MainPresenter constructor( | |
private val view: MainContract.View | |
): MainContract.Presenter { | |
/* ... */ | |
} | |
@AndroidEntryPoint | |
class MainActivity : AppCompatActivity(), MainContract.View { | |
@Inject lateinit var presenter: MainContract.Presenter | |
/* ... */ | |
} | |
@Module | |
@InstallIn(ActivityComponent::class) | |
object MainActivityModule { | |
/* Solution to provide the MainActivity instance */ | |
@Provides | |
fun provideView(activity: Activity): MainContract.View = activity as MainContract.View | |
@Provides | |
fun providerMainPresenter(view: MainContract.View): MainContract.Presenter = MainPresenter(view) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment