在我的应用程序中,我有片段,在这个片段中我使用了LiveData。
我在使用 LiveData 时遇到问题。
我在片段中写下以下代码:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Get id
viewModel.productID.observe(viewLifecycleOwner) {
productID = it
}
//InitViews
binding.apply {
//Submit
submitBtn.setOnClickListener {
val rate = rateSlider.value.toInt().toString()
val comment = commentEdt.text.toString()
body.rate = rate
body.comment = comment
viewModel.callPostCommentApi(productID, body)
}
}
//Load data
loadNewCommendData()
}
private fun loadNewCommendData() {
binding.apply {
viewModel.addNewCommentData.observe(viewLifecycleOwner) { response ->
when (response) {
is NetworkRequest.Loading -> {
submitBtn.enableLoading(true)
}
is NetworkRequest.Success -> {
submitBtn.enableLoading(false)
response.data?.let { data ->
Toast.makeText(requireContext(), data.message, Toast.LENGTH_LONG).show()
[email protected]()
}
}
is NetworkRequest.Error -> {
submitBtn.enableLoading(false)
root.showSnackBar(response.message!!)
}
}
}
}
}
我的问题:调用 API 并显示 Toast 消息后,我关闭了 fragment 但是当我想再次打开 fragment 时,不打开 fragment 并且只显示 Toast 消息。
Toast消息:
Toast.makeText(requireContext(), data.message, Toast.LENGTH_LONG).show()
我写下面的功能:
fun <T> LiveData<T>.onceObserve(owner: LifecycleOwner, observe: Observer<T>) {
observe(owner, object : Observer<T> {
override fun onChanged(value: T) {
removeObserver(this)
observe.onChanged(value)
}
})
}
使用该函数时,只调用NetworkRequest.Loading,不调用NetworkRequest.Success或NetworkRequest.Error!!!
我该如何解决?
如果你使用像下面的代码一样实现'onceObserve'来观察你的liveDatas,问题应该得到解决
viewModel.productID.onceObserve(viewLifecycleOwner) {
productID = it
}
viewModel.addNewCommentData.onceObserve(viewLifecycleOwner) { response -> { //Your code goes here}