I am new in Android MVVM, let say I have 2 screens to show, Fragment A and Fragment B.
when user click a button in Fragment A, then I check to server if this user has created an event or not, it he has not created an event then move to Fragment B. here is my FragmentA
class FragmentA : Fragment() {
lateinit var model: AViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
model = ViewModelProvider(this).get(AViewModel::class.java)
button.setOnClickListener {
model.checkIfUserHasCreatedEvent()
}
model.hasCreatedEvent.observe(this, Observer { hasCreatedEvent ->
if (!hasCreatedEvent) {
val chooseEventNameDestination = CreateEventFragmentDirections.actionToCreateEventName()
findNavController().navigate(chooseEventNameDestination)
}
})
}
}
and here the view model for fragmentA
class AViewModel(application: Application) : AndroidViewModel(application) {
val hasCreatedEvent = UserRepository.hasCreatedEvent
fun checkIfUserHasCreatedEvent() {
UserRepository.checkIfUserHasReachedMaxEventCreationForToday()
}
}
if the user has not created an event (hasCreatedEvent == false)
then he will go from Fragment A to Fragment B. but the problem is, when I want to back again from Fragment B to fragmentA
the observer for hasCreatedEvent
seems automatically give false
value
model.hasCreatedEvent.observe(this, Observer { hasCreatedEvent ->
// hasCreatedEvent will always be false when I back from fragment B to fragment A
if (!hasCreatedEvent) {
// thats why the block here will be triggered immediately
// and I will move back to fragmentB again
// I want to stay at FragmentA, after back from FragmentB
val chooseEventNameDestination = CreateEventFragmentDirections.actionToCreateEventName()
findNavController().navigate(chooseEventNameDestination)
}
})
I expect hasCreatedEvent
will be null when I back from fragmentB to fragmentA. what should I do ? is it a correct behaviour ?
kotlin or java are ok