Reputation: 69
So I have this code that when i press a button
btnLogin.setOnClickListener {
val user = UserLogin(etUsername.text.toString(), etPassword.text.toString())
viewModel.login(user)
}
I will observe this
fun login(user: UserLogin) {
loginGateway.loginBuyer(user)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe { _loginState.postValue(LoginLoading) }
.subscribe({
if(it.data != null)
_loginState.postValue(LoginSuccess(it.data))
else
_loginState.postValue(LoginFailed(it.message))
}, {
_loginState.postValue(LoginError(it.localizedMessage))
})
.addTo(disposable)
}
and here is the observer
viewModel.loginState.observe(this, Observer {it ->
when (it) {
LoginLoading -> {
dialog.show()
}
is LoginSuccess -> {
dialog.dismiss()
if (cbRemember.isChecked)
viewModel.saveUsername(etUsername.text!!.toString())
viewModel.saveFirstname(it.user.firstName)
findNavController().navigate(R.id.toMain)
}
is LoginFailed -> {
dialog.dismiss()
showErrorDialog(this.context!!, "Login Failed", it.message)
}
is LoginError -> {
dialog.dismiss()
showErrorDialog(this.context!!, "Login Error", it.message)
}
}
})
So this is the problem when I have failed a login so it will show a dialog and when dismissed and when I go to register page and go back to login the same dialog still appears.
I tried doing like putting removeObservers(this)
on the onPause() and onDestroy() but its still the same. I'm not quite sure if the problem lies with the fragment lifecycle if not please help me understand whats happening. I'm new with kotlin and mvvm so please. Thanks :)
Upvotes: 1
Views: 786
Reputation: 1
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewModel.isDialogOpen.observe(viewLifecycleOwner) { isDialogOpen ->
if (!isDialogOpen) {
[email protected]()
}
}
}
I have a set btn, When the set btn is clicked, I set this variable isDialogOpen to false ,sometimes ,obsever is not working and it is not coming into if condition .
Upvotes: 0
Reputation: 39873
The field viewModel.loginState
is like it's named a state which lives within the viewModel
. When you navigate to the navigation, the observation will be suspended, but also restarted after you navigate back. Since you don't change the state itself, maybe only dismiss the dialog, you'll end up with the same screen as before.
So just update the state to a more relevant value when you dismiss the dialog.
Upvotes: 1