我们可以在不失去任何价值的情况下使用Livedata吗?



我想在自定义视图及其包装片段之间使用livedata来处理这种通知。但是看来,寿命可能会失去价值:它只会更新到其最近的状态,并且在其观察者的不活动状态下也不会发射值。

我已经研究了Google代码样本中的单层次词,但是该解决方案似乎还没有进行战斗,并且票仍在最近尝试改进解决方案的情况下开放。

因此,我正在寻找一种简单的方法来通知事件,同时不担心生命周期(这就是为什么我选择Livedata作为第一个解决方案(,并且可以处理多个观察者。p>有现有的解决方案吗?如果我尝试实施它,可以肯定我将至少陷入反pattern。

一种简单的方法(也许太容易(是使用回调:但是问题在于,我需要此功能才能在组件中的几个回调中进行此功能,从而使我进入了一个糟糕的体系结构。而且,我想要一个订阅系统,这意味着可能有多个观察者。

另一种方式可能是使用rxjava并将其变形为livedata,而liveataTareActivEstreams.frompublisher((:但是现在问题是我是要获得所有值还是只有最后一个值。那是我可以处理的最接近的解决方案。

作为一个有趣的替代方案,可以有自动化或rxlifecycle。和我发现的一个有趣的资源:Livedata上的博客文章

您的想法是什么?

另外,请注意,我需要从包裹到片段(棋盘(到另一个片段(棋盘((棋盘(的组件(棋盘((棋盘((棋盘(。因此,他们都知道生命周期。

这不是理想的选择,但这对我来说很有困难:

/**
* This LiveData will deliver values even when they are 
* posted very quickly one after another.
*/
class ValueKeeperLiveData<T> : MutableLiveData<T>() {
    private val queuedValues: Queue<T> = LinkedList<T>()
    @Synchronized
    override fun postValue(value: T) {
        // We queue the value to ensure it is delivered 
        // even if several ones are posted right after.
        // Then we call the base, which will eventually
        // call setValue().
        queuedValues.offer(value)
        super.postValue(value)
    }
    @MainThread
    @Synchronized
    override fun setValue(value: T) {
        // We first try to remove the value from the queue just
        // in case this line was reached from postValue(),
        // otherwise we will have it duplicated in the queue.
        queuedValues.remove(value)
        // We queue the new value and finally deliver the
        // entire queue of values to the observers.
        queuedValues.offer(value)
        while (!queuedValues.isEmpty())
            super.setValue(queuedValues.poll())
    }
}

此解决方案的主要问题是,如果观察者在值通过super.setValue()传递时不活动,那么无论如何,值将丢失。但是,当几个新值很快发布时,它解决了丢失价值的问题 - 我认为,这通常是一个比失去价值观更大的问题,因为您的观察者是不活动的。毕竟,您始终可以从非差异的对象进行myLiveData.observeForever(),以接收所有通知。

不确定这对您而言是否足够,但我希望它可以帮助您或给您一些有关如何实施自己的方法的想法。

最新更新