我正在使用 MVVM 架构。
编码
当我单击一个按钮时,会触发orderAction方法。它只是发布一个枚举(将添加进一步的逻辑)。
视图模型
class DashboardUserViewModel(application: Application) : SessionViewModel(application) {
enum class Action {
QRCODE,
ORDER,
TOILETTE
}
val action: LiveData<Action>
get() = mutableAction
private val mutableAction = MutableLiveData<Action>()
init {
}
fun orderAction() {
viewModelScope.launch(Dispatchers.IO) {
// Some queries before the postValue
mutableAction.postValue(Action.QRCODE)
}
}
}
片段观察 LiveData obj 并调用打开新片段的方法。我在这里使用导航器,但我认为有关它的详细信息在这种情况下没有用处。请注意,我正在使用viewLifecycleOwner
分段
class DashboardFragment : Fragment() {
lateinit var binding: FragmentDashboardBinding
private val viewModel: DashboardUserViewModel by lazy {
ViewModelProvider(this).get(DashboardUserViewModel::class.java)
}
private val observer = Observer<DashboardUserViewModel.Action> {
// Tried but I would like to have a more elegant solution
//if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED)
it?.let {
when (it) {
DashboardUserViewModel.Action.QRCODE -> navigateToQRScanner()
DashboardUserViewModel.Action.ORDER -> TODO()
DashboardUserViewModel.Action.TOILETTE -> TODO()
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDashboardBinding.inflate(inflater, container, false)
binding.viewModel = viewModel
binding.lifecycleOwner = this
viewModel.action.observe(viewLifecycleOwner, observer)
// Tried but still having the issue
//viewModel.action.reObserve(viewLifecycleOwner, observer)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
// Tried but still having the issue
//viewModel.action.removeObserver(observer)
}
private fun navigateToQRScanner() {
log("START QR SCANNER")
findNavController().navigate(LoginFragmentDirections.actionLoginToPrivacy())
}
}
问题
当我关闭打开的片段(使用 findNavController().navigateUp())时,会立即调用 DashboardFragment 的 Observe.onChanged 并再次打开片段。
我已经检查了这个问题并尝试了上述链接中提出的所有解决方案(如您在注释代码中所见)。只有这个解决方案有效,但它不是很优雅,并迫使我每次都进行检查。
我想尝试一个更可靠和最优的解决方案。
请记住,在该线程中没有生命周期实现。