弹出上一个片段时,如何阻止观察者自动观察数据?

时间:2020-03-19 04:48:43

标签: android kotlin android-livedata android-viewmodel android-mvvm

我是Android MVVM的新手,可以说我有2个屏幕要显示,片段A和片段B。

当用户单击“片段A”中的按钮时,然后我检查服务器是否该用户已创建事件,他是否尚未创建事件,然后移至片段B。这是我的“片段A”

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)

            }

        })



    }

}

和这里的fragmentA的视图模型

class AViewModel(application: Application) : AndroidViewModel(application) {

    val hasCreatedEvent = UserRepository.hasCreatedEvent

    fun checkIfUserHasCreatedEvent() {
        UserRepository.checkIfUserHasReachedMaxEventCreationForToday()

    }


}

如果用户尚未创建事件(hasCreatedEvent == false),那么他将从片段A转到片段B。但是问题是,当我想再次从片段B返回片段A

hasCreatedEvent的观察者似乎自动给了false

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)

     }

 })

我希望当我从fragmentB回到fragmentA时,hasCreatedEvent将为空。我该怎么办 ?这是正确的行为吗?

kotlin或java都可以

0 个答案:

没有答案