Multiple calls to set LiveData is not observed

后端 未结 5 1037
闹比i
闹比i 2021-01-11 18:28

I have recently seen a weird issue that is acting as a barrier to my project. Multiple calls to set the live data value does not invoke the observer in the view.

It

5条回答
  •  伪装坚强ぢ
    2021-01-11 18:52

    I had such issue too.

    To resolve it was created custom MutableLiveData, that contains a queue of posted values and will notify observer for each value.

    You can use it the same way as usual MutableLiveData.

    open class MultipleLiveEvent : MutableLiveData() {
    private val mPending =
        AtomicBoolean(false)
    private val values: Queue = LinkedList()
    
    @MainThread
    override fun observe(
        owner: LifecycleOwner,
        observer: Observer
    ) {
        if (hasActiveObservers()) {
            Log.w(
                this::class.java.name,
                "Multiple observers registered but only one will be notified of changes."
            )
        }
        // Observe the internal MutableLiveData
        super.observe(owner, Observer { t: T ->
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t)
                //call next value processing if have such
                if (values.isNotEmpty())
                    pollValue()
            }
        })
    }
    
    override fun postValue(value: T) {
        values.add(value)
        pollValue()
    }
    
    private fun pollValue() {
        setValue(values.poll())
    }
    
    @MainThread
    override fun setValue(t: T?) {
        mPending.set(true)
        super.setValue(t)
    }
    
    /**
     * Used for cases where T is Void, to make calls cleaner.
     */
    @Suppress("unused")
    @MainThread
    fun call() {
        value = null
    }
    

    }

提交回复
热议问题