android - 弹出回到上一个片段时如何停止观察者自动观察数据?
问题描述
我是 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 都可以
解决方案
推荐阅读
- python - pandas 按年份分组数据并根据多(二)列给出排名
- java - rxjava2中的zip函数问题
- asp.net - 在 openId 授权代码流中使用最新版本的 Katana DLL 自动兑换代码(授权代码)
- amazon-web-services - 无法删除 S3 对象
- java - 更换 Fragment android 后 Ram 使用量增加
- android - 如何将 RxJava 代码改进为 API 和本地缓存?
- python - 训练使用 tensorflow.keras.Model 和 keras 功能 API 设计的网络会导致 Python 崩溃
- ios - 过滤器不适用于tableView Swift中的搜索栏UITextField
- java - Aerospike - 如何使用 Java 在给定列表中插入唯一项?
- python - 实现python的测试功能时出错