【发布时间】:2021-06-20 02:46:37
【问题描述】:
所以我正在尝试使用导航组件实现 mvvm 架构,这段代码片段工作得很好。问题是当我从 fragmentA 导航到 FragmentB 时,没有办法回到 FragmentA,就像按钮一样被阻止(如果我删除 ViewModel,导航可以正常工作,因此它与 ViewModel 有关)。
有人知道发生了什么吗?
private fun initVewModel() {
myViewModel = MyViewModel()
myViewModel = ViewModelProviders
.of(this, createFor(myViewModel))
.get(MyViewModel::class.java)
}
private fun setupObservers() {
myViewModel.myData.observe(viewLifecycleOwner, Observer {
it?.let { resource ->
when (resource.status) {
Status.SUCCESS -> {
resource.data?.let {
val action =
FragmentADirections.actionFragmentAToFragmentB()
Navigation.findNavController(requireView()).navigate(action)
}
}
Status.ERROR -> {
//TODO show an error
loading.visibility = View.GONE
}
Status.LOADING -> {
loading.visibility = View.VISIBLE
}
}
}
})
}
这是我的视图模型
class MyViewModel : ViewModel() {
private val searchText = MutableLiveData<String>()
//This method is called on a search button click
fun setSearchText(text: String) {
searchText.value = text
}
val myData = searchText.switchMap { text ->
liveData(Dispatchers.IO) {
emit(Resource.loading(data = null))
try {
emit(Resource.success(data = dataOrigin.getData(text)))
} catch (exception: Exception) {
exception.printStackTrace()
emit(Resource.error(data = null, message = exception.message ?: "Error Occurred!"))
}
}
}
}
【问题讨论】:
标签: android kotlin mvvm android-jetpack android-mvvm