【问题标题】:How to Avoid Race Condition in FragmentManager?如何避免 FragmentManager 中的竞争条件?
【发布时间】:2021-11-23 06:40:34
【问题描述】:

我的目标是在片段堆栈中只允许同一对话框片段的一个实例。

当前触发条件来自 SharedFlow,并且可以在值之间以7ms 的频率触发。

这是我尝试过的:

  1. 将代码放在synchronized 块中
  2. 通过调用fm.findFragmentByTag检查现有片段是否在堆栈中

但是,这两个条件都不足以阻止fragment多次添加到fragmentManager中。

我尝试使用dialogFragment.showNow(fm, tag),但它不稳定且崩溃

感谢任何帮助。


override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  viewModel.someSharedFlow
    .flowWithLifecycle(viewLifecycleOwner.lifecycle)
    .onEach { showMyFragmentDialog() }
    .launchIn(viewLifecycleOwner.lifecycleScope)
}

private fun showMyFragmentDialog() {
  synchronized(childFragmentManager) {
    if (childFragmentManager.findFragmentByTag(MyFragment.TAG) == null) {
      MyFragment.newInstance(fuelTypes)
        .show(childFragmentManager, MyFragment.TAG)
    }
  }
}

【问题讨论】:

    标签: android race-condition android-dialogfragment fragmentmanager kotlin-sharedflow


    【解决方案1】:

    暂时使用协程。不理想,但至少可以正常工作。

    private var myLaunchJob: Job? = null
    private fun showMyFragmentDialog() {
      if (myLaunchJob?.isActive == true) return
      myLaunchJob = viewLifecycleOwner.lifecycleScope.launch {
        if (childFragmentManager.findFragmentByTag(MyFragment.TAG) == null) {
          MyFragment.newInstance(fuelTypes)
            .show(childFragmentManager, MyFragment.TAG)
        }
        // Act as debouncer
        delay(1000)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 2015-01-30
      • 2010-09-25
      相关资源
      最近更新 更多