[英]LiveData Observer triggers when not needed
我有一個視圖模型,它從場景中接收流作為實時數據
val state get () = syncScenario.state.asLiveData ()
在活動中,我們訂閱了這個實時數據,發生了一些邏輯並使用了 activityResult
private val resultLauncher = registerForActivityResult (activityResult ()) {result ->
when (result.resultCode) {
Activity.RESULT_OK -> sync()
Activity.RESULT_CANCELED -> return
}
}
當我們返回時,我們有一個觀察者被最后一個 state 觸發,並且再次執行之前的導航邏輯
private val syncStateObserver = Observer<StateInfo?> {
it?: return@Observer
when (it) {
is Guest -> doWhenUserIsGuest()
is Authorized -> doWhenUserIsAuthorized()
}
}
如何忽略返回值相同的觀察者觸發器?
對此有一個流行的答案。 您可以使用SingleEvent
class 包裝您的StateInfo
:
open class SingleEvent<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
}
所以你的觀察者看起來像下面這樣:
private val syncStateObserver = Observer<SingleEvent<StateInfo>> {
it.getContentIfNotHandled()?: return@Observer
when (it.peek()) {
is Guest -> doWhenUserIsGuest()
is Authorized -> doWhenUserIsAuthorized()
}
}
這個 url 對我有幫助 - https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150
但不適用於 livedata.ktx -> liveData{ syncScenario.state.collect { emit(Wrapper(it))} }
我通過制作一種方法解決了這個問題,在該方法中我從流中收集數據並將其放入帶有包裝器的可變實時數據中 url
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.