I've a fragment making a network request based on the result, I'm navigating to the next fragment.
I am not able to go back to the previous fragment, this is the issue: https://streamable.com/4m2vzg
This is the code in the previous fragment
class EmailInputFragment :
BaseFragment<FragmentEmailInputBinding>(FragmentEmailInputBinding::inflate) {
private val viewModel by viewModels<EmailInputViewModel>()
private lateinit var progressButton: ProgressButton
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.emailToolbar.setNavigationOnClickListener {
val activity = activity as AuthActivity
activity.onSupportNavigateUp()
}
binding.emailNextButton.pbTextview.text = getString(R.string.next)
binding.emailNextButton.root.setOnClickListener {
checkValidEmail()
}
binding.enterEmail.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
checkValidEmail()
}
false
}
binding.enterEmail.doAfterTextChanged {
binding.enterEmailLayout.isErrorEnabled = false
}
viewLifecycleOwner.lifecycleScope.launch {
viewModel.emailCheck.collect {
when (it) {
State.Empty -> {
}
is State.Failed -> {
Timber.e(it.message)
progressButton.buttonFinished("Next")
}
State.Loading -> {
progressButton.buttonActivate("Loading")
}
is State.Success<*> -> {
it.data as EmailCheckModel
when (it.data.registered) {
// New User
0 -> {
findNavController().navigate(
EmailInputFragmentDirections.actionEmailFragmentToSignupFragment(
binding.enterEmail.text.toString().trim()
)
)
}
// Existing User
1 -> {
findNavController().navigate(
EmailInputFragmentDirections.actionEmailFragmentToPasswordInputFragment(
binding.enterEmail.text.toString().trim()
)
)
}
// Unverified user
2 -> {
findNavController().navigate(
EmailInputFragmentDirections.actionEmailFragmentToVerifyUserFragment(
"OK"
)
)
}
}
}
}
}
}
}
private fun checkValidEmail() {
if (!binding.enterEmail.text.toString().trim().isValidEmail()) {
binding.enterEmailLayout.error = "Please enter valid Email ID"
return
}
progressButton = ProgressButton(requireContext(), binding.emailNextButton.root)
viewModel.checkUser(binding.enterEmail.text.toString().trim())
}
}
When I press back from the next fragment, as the state is still Success the flow is being collected and goes to next fragment, I've tried this.cancel to cancel the coroutine on create and still doesn't work. How do I go about this?
Moving the flow collect to the onClick of the button throws a error that navigation action cannot be found for the destination
I put a workaround of resetting the state of the flow back to State.EMPTY on success using
viewModel.resetState()
in onSuccess, I don't think this is the best way, any suggestions?
ViewModel code:
private val _emailCheckResponse = MutableStateFlow<State>(State.Empty)
val emailCheck: StateFlow<State> get() = _emailCheckResponse