gpt4 book ai didi

ios - ReactiveCocoa : release a RACSignal when no one subscribes it

转载 作者:行者123 更新时间:2023-12-01 16:28:20 24 4
gpt4 key购买 nike

在我的类里面,应用程序的其他部分可能会观察到一些值。这些值可以读取和写入数据库。

我有一个保留一些 RACSubjects 的集合。

当一个对象需要观察一个值时V1 ,我将创建一个 RACSignal给它起个名字S1 , 稍后如果任何其他对象也对 V1 感兴趣,我给它V1也一样,这样当 S1 改变时,我可以调用 [RACSubject sendNext:]通知对它感兴趣的对象。

但是有一个问题,不知道什么时候发布S1 ,因为我不知道当没有对象订阅 S1 时如何获得通知。

有没有办法做到这一点?

最佳答案

我在精神上将您问题的一部分改写为以下内容(我的更改以斜体显示),因为我认为原始措辞有一些错别字:

When an object need to observe a value V1, I'll create a RACSubject for it, name it S1, and later if any other object is also interested in V1, I'll give it S1 too, so that when V1 changed, I can call [RACSubject sendNext:] to notify objects that is interested in it.



如果这是不正确的解释,请忽略此答案。

如果您自己没有明确保留信号, ReactiveCocoa will automatically reclaim it when it runs out of subscribers .相关摘录:

  1. A created signal is automatically added to a global set of active signals.
  2. The signal will wait for a single pass of the main run loop, and then remove itself from the active set if it has no subscribers. Unless the signal was retained somehow, it would deallocate at this point.
  3. If something did subscribe in that run loop iteration, the signal stays in the set.
  4. Later, when all the subscribers are gone, step 2 is triggered again.


但是有一个问题:这不适用于 RACSubject s。它们不会添加到全局事件信号集中。

但是,您可以应用一种解决方法来获得这种良好的自动保留行为。
RACSignal *autoretainedSignal = [subject map:^(id x) { return x; }]

只要您只订阅 autoretainedSignal ,而不是基础 RACSubject ,您可以利用正常信号获得的自动保留行为。

那么如何在不保留的情况下保留它呢?如果您只有一个信号表明您对缓存/共享感兴趣,则可以将其存储在弱属性中。如果您正在动态管理多个属性, NSMapTable 弱存储是你的 friend 。

您需要同时保留基础主题(以便您可以在其上发送事件)和派生信号(以便您可以将其提供给订阅者)。只要派生信号有订阅者,它就会保持其基础主题处于事件状态,并且一旦它用完订阅者,它和它的主题都将被解除分配。

关于ios - ReactiveCocoa : release a RACSignal when no one subscribes it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com