Search code examples
androidandroid-livedataandroid-viewmodelkoin

Android viewmodel observing always


I am using KoinDI and I have a login screen. Here is my code -

My AppModule code which shows LoginViewModel DI definition -

private val viewModelModules = module {
    viewModel { LoginViewModel(get()) }
}

My LoginFragment code -

private val viewModel: LoginViewModel by viewModel()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    view.login_button?.setOnClickListener {
        onLoginButtonPressed()
    }
}

private fun onLoginButtonPressed() {
        val email = view?.email_value?.text.toString()
        val password = view?.password_value?.text.toString()

        viewModel.onLoginPressed(email, password).observe(this, Observer {

                if (it.userLoggedIn) {
                    //...
                }
                handleError(it.error)

        })
}

The problem is when I click login and immediately put the app in background and API call fails (I fail it on purpose for testing from the backend side) and when I bring the app in foreground I see that the viewmodel continues to observe resulting in API call happening again and again until it succeeds. Why does it happen? Why cannot my viewmodel observe only on login button click?


Solution

  • When you say viewModel.onLoginPressed.observe the activity/fragment will receive events when it is started or resumed state and when it is destroyed the observer will automatically be removed.

    You seem to have a retry logic inside the viewModel that keep retrying.