KunMinX / UnPeek-LiveData

LiveData 数据倒灌:别问,问就是不可预期 - Perfect alternative to SingleLiveEvent, supporting multiple observers.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

其实这样就可以了,不需要包一层

jackjustbj opened this issue · comments

open class ProtectedUnPeekLiveData<T : Any?> : LiveData<T?>() {

    private val pending = AtomicBoolean(false)
    protected var isAllowNullValue = false

    override fun observe(owner: LifecycleOwner, observer: Observer<in T?>) {
        super.observe(owner) { t ->
            if (pending.compareAndSet(true, false)
                && (t != null || isAllowNullValue)
            ) {
                observer.onChanged(t)
            }
        }
    }

    override fun observeForever(observer: Observer<in T?>) {
        super.observeForever { t ->
            if (pending.compareAndSet(true, false)
                && (t != null || isAllowNullValue)
            ) {
                observer.onChanged(t)
            }
        }
    }

    fun observeSticky(owner: LifecycleOwner, observer: Observer<T?>) {
        super.observe(owner, observer)
    }

    fun observeStickyForever(observer: Observer<T?>) {
        super.observeForever(observer)
    }

    override fun setValue(value: T?) {
        if (value != null || isAllowNullValue) {
            pending.set(true)
            super.setValue(value)
        }
    }

    fun clear() {
        super.setValue(null)
    }
}

多观察者时不可简化成这样