0

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

Alexa289
  • 8,089
  • 10
  • 74
  • 178
  • the solution for this: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150#0e87 – Alexa289 Mar 19 '20 at 05:58
  • You can use SingleLiveEvent Class. Check this: https://www.google.com/search?q=SingleLiveEvent&oq=SingleLiveEvent&aqs=chrome..69i57.5103j0j1&sourceid=chrome&ie=UTF-8 – Satwinder Singh Apr 05 '20 at 07:35

0 Answers0