我在函式中有一個觀察者。我首先在我的活動中呼叫這個函式onCreate(),它作業正常。之后,當我再次呼叫這個函式時,觀察者內部的代碼被呼叫了兩次。我怎樣才能防止這種行為?
這是我與觀察者的功能
private lateinit var word: String
fun addViews() {
viewModel.getQuestion()
viewModel.questionResponse.observe(this, { it ->
this.word = it.data.word
createAnswerTextView(this.word.length)
}
})
}
編輯:
我想要做的是通過在這些步驟中洗掉和添加視圖來重繪 布局。
- 創建與字長一樣長的文本視圖。(
addViews()為我做) - 洗掉這些視圖。
- 只要新的字長就可以再次創建文本視圖。(
addViews()為我做)
我不能在活動的onCreate()方法中只創建一次觀察者。因為我需要多次使用 addViews 函式及其觀察者。
viewModel.questionResponse.removeObservers(this) 也沒有用。
但是添加viewModel.questionResponse = MutableLiveData()洗掉文本視圖的函式并清除我的屬性值解決了我的問題。
uj5u.com熱心網友回復:
如果您在片段中作業,則必須在“onViewCreated”中定義觀察者,如果在活動中作業,則必須在 onCreateView 中定義觀察者。
此外,在您的片段中,您應該將視圖模型定義為:
val yourviewModel by activityViewModels<YourViewModel>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
yourviewModel.yourVariable.observe(viewLifecycleOwner) {
// some function to do
}
}
在您的活動中:
val yourviewModel by viewModels<YourViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
yourviewModel.yourVariable.observe(this) {
// some function to do
}
}
如果您不想這樣做,還有另一種方法,它只是洗掉所有觀察者:
fun addViews() {
viewModel.getQuestion()
// add this line
viewModel.questionResponse.removeObservers(this)
viewModel.questionResponse.observe(this, { it ->
this.word = it.data.word
createAnswerTextView(this.word.length)
}
})
}
uj5u.com熱心網友回復:
始終onCreate在活動中呼叫內部觀察者。每次呼叫addViews()函式時都在注冊觀察者。只需將下面的代碼移動到 onCreate 內部
viewModel.questionResponse.observe(this, { it ->
this.word = it.data.word
createAnswerTextView(this.word.length)
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341616.html
標籤:安卓 科特林 虚拟机 android-livedata 观察员
