I'm learning dependency injection by the article with the project。
The Code A need instance an object navigator
by dependency injection , so the author use Code B to implement it, you can see it here.
I'm very strange that the class AppNavigatorImpl
has implemented the class AppNavigator
by dependency injection in Code C, so I think Code D will work well.
Can I use @Inject lateinit var navigator: AppNavigatorImpl
instead of @Binds abstract fun bindNavigator(impl: AppNavigatorImpl): AppNavigator
?
Code A
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var navigator: AppNavigator
...
}
Code B
@InstallIn(ActivityComponent::class)
@Module
abstract class NavigationModule {
@Binds
abstract fun bindNavigator(impl: AppNavigatorImpl): AppNavigator
}
Code C
class AppNavigatorImpl @Inject constructor(private val activity: FragmentActivity) : AppNavigator {
override fun navigateTo(screen: Screens) {
val fragment = when (screen) {
Screens.BUTTONS -> ButtonsFragment()
Screens.LOGS -> LogsFragment()
}
activity.supportFragmentManager.beginTransaction()
.replace(R.id.main_container, fragment)
.addToBackStack(fragment::class.java.canonicalName)
.commit()
}
}
Code D
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject lateinit var navigator: AppNavigatorImpl
...
}