asterixorobelix
asterixorobelix

Reputation: 138

Reference activity in koin Module

I have a single activity application.

My MainActivity is referenced in a number of dependency injection modules, as the implementer of these interfaces. I currently have a work around, which is less than ideal.

class MainActivity : TransaktActivity(), RegistrationNavigator, IAuthPresenter,
    IAuthButtonNavigator {

    override fun navigateAwayFromAuth() {
        navController.navigate(R.id.homeFragment)
    }

    override fun navigateToAuthPin(buttonId: Int) {
        //todo navigate to auth with pin fragment
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _mainActivity = this
        setContentView(R.layout.activity_main)
    }

    companion object {
        private var _mainActivity: MainActivity? = null

        fun getInstance() = _mainActivity
    }
}
interface RegistrationNavigator {
    fun navigateToCardDetails()
    fun navigateToOtpCapture()
    fun navigateToLoading()
    fun navigateOutOfCardRegistration()
}

The appModule is a Koin Module

val appModule = module {
    viewModel { SharedViewModel() }

    single { MainActivity.getInstance() as RegistrationNavigator }
}

What is the preferred way of achieving this?

Upvotes: 1

Views: 2225

Answers (1)

laalto
laalto

Reputation: 152787

Android-lifecycled components such as activities should not be in koin modules.

For example you will have issues with e.g. configuration changes since the koin module would be serving references to stale activity after the activity is recreated.

I haven't really worked with NavController but rather rolled up my own navigation solution. As a generic approach I would refactor the RegistrationNavigator implementation to a separate class the instance of which you can provide from your koin module. If lifecycle-dependent params such as Context (or NavController) are needed, supply them as function args.

Upvotes: 1

Related Questions