简体   繁体   中英

LiveData Observer triggers when not needed

I have a viewmodel that receives flow as livedata from scenario

val state get () = syncScenario.state.asLiveData ()

In the activity, we subscribe to this livedata, some logic happens and used the activityResult

private val resultLauncher = registerForActivityResult (activityResult ()) {result ->
         when (result.resultCode) {
             Activity.RESULT_OK -> sync()
             Activity.RESULT_CANCELED -> return
         }
     }

when we return, we have an observer triggered with the last state and the previous logic with navigation is performed again

private val syncStateObserver = Observer<StateInfo?> {
        it?: return@Observer

        when (it) {
            is Guest -> doWhenUserIsGuest()
            is Authorized -> doWhenUserIsAuthorized()
        }
    }

How can you ignore an observer trigger with the same value on return?

There is a popular answer for this. You can wrap your StateInfo with SingleEvent class:

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
}

So your observer looks like below:

private val syncStateObserver = Observer<SingleEvent<StateInfo>> {
        it.getContentIfNotHandled()?: return@Observer

        when (it.peek()) {
            is Guest -> doWhenUserIsGuest()
            is Authorized -> doWhenUserIsAuthorized()
        }
}

this url is help me - https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

but doesn't work for livedata.ktx -> liveData{ syncScenario.state.collect { emit(Wrapper(it))} }

I solved this by making a method in which I collect data from the flow and put it in my mutable livedata with wrapper from url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM