Ric*_*ues 3 android observers kotlin
我有一个观察者,而不是当它被称为更改片段时。
问题是当我返回时,立即调用观察者,并且我的应用程序崩溃了
java.lang.IllegalArgumentException:导航目标 com.superapps.ricardo.tablepro:id/action_searchFragment_to_yourGameList2 对于此 NavController 来说是未知的。
我不明白为什么会这样称呼它。
这是更改列表的唯一方法
override fun onSuccess(gamePair: Pair<Int, List<BggGame>>) {
CoroutineScope(Main).launch{
//goToList(gamePair.second, binding.input.text.toString())
viewModel.setGameList(gamePair.second)
}
}
Run Code Online (Sandbox Code Playgroud)
这是视图模型创建和更改片段代码
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(SearchViewModel::class.java)
viewModel.gameList.observe(viewLifecycleOwner, Observer {
goToList(it, binding.input.text.toString())
})
}
private fun goToList(games: List<BggGame>, user: String) {
val action = SearchFragmentDirections.actionSearchFragmentToYourGameList2(user)
val gameList = GameList()
gameList.gameList = games
action.gameList = gameList
try {
Navigation.findNavController(view!!).navigate(action)
viewModel.gameList.removeObservers(viewLifecycleOwner)
} catch (e: Exception){
Log.e("a0,","a..", e)
}
progressDialog.dismiss()
}
Run Code Online (Sandbox Code Playgroud)
LiveData保留最后设置的值。当调用observe()a 时LivaData,如果 aLiveData有值,则立即使用先前设置的值调用观察者。
如果您想用于LiveData像您的用例这样的“事件”,您的实时数据应该公开一个Event只能使用一次的对象。
下面是此类的良好实现的示例Event。
来自文章:
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
Run Code Online (Sandbox Code Playgroud)
在 ViewModel 中的用法:
val gameList = MutableLiveData<Event<List<BggGame>>()
fun setGameList(gameList: List<BggGame>) {
gameList.value = Event(gameList)
}
Run Code Online (Sandbox Code Playgroud)
视图中的用法:
viewModel.gameList.observe(this, Observer {
it.getContentIfNotHandled()?.let { // Only proceed if the event has never been handled
goToList(it, binding.input.text.toString())
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1644 次 |
| 最近记录: |