首页 > 解决方案 > 弹出回到上一个片段时如何停止观察者自动观察数据?

问题描述

我是 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)

     }

 })

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

kotlin 或者 java 都可以

标签: androidkotlinandroid-livedataandroid-viewmodelandroid-mvvm

解决方案


推荐阅读