I have Alert Dialog opened from fragment, It have two edittext and one button, one edittext will be visible at a time. On clicking submit, call API -> based on response -> second edittext will be visible. Im using ViewModel and LiveData for listening for response.
Problem: How to correctly observe live data within Alert Dialog context?
val dialogBinding: DialogTestBinding = DialogTestBinding.inflate(layoutInflater)
val dialog = AlertDialog.Builder(requireContext()).create()
dialogBinding.edtMobile.setText(viewModel.userMobile)
dialogBinding.submit.setOnClickListener {
if (dialogBinding.edtMobile.visibility == View.VISIBLE) {
//observing live data with viewLifecycleOwner - how to correctly manage for alert dialog//
viewModel.newNumber.observe(viewLifecycleOwner) {
dialogBinding.edtOtp.visibility = View.VISIBLE
dialogBinding.edtMobile.visibility = View.GONE
//viewModel.newNumber.removeObservers(viewLifecycleOwner)
}
val newNumber = dialogBinding.edtMobile.text.toString()
callAPI(newNumber, "")
} else {
val newNumber = dialogBinding.edtMobile.text.toString()
val otp = dialogBinding.edtOtp.text.toString()
callAPI(newNumber, otp)
}
}
dialog.setView(dialogBinding.root)
dialog.show()
This is working but it will listen for the change even after the AlertDialog is dismissed. Is there any option other than removing the Observer manually?