【问题标题】:RxJava- No access to Observable's subscribers?RxJava- 无法访问 Observable 的订阅者?
【发布时间】:2015-05-12 16:21:24
【问题描述】:

我学会了it is undesirable 在反应式编程中使用Subjects,尽管我发现它们非常方便。但我知道他们可能会被滥用。所以我尝试创建一个无限的Observable<ImmutableMap<Integer,ActionProfile>,每次调用refresh() 时都需要发布一个新的ImmutableMap。我还有一个forKey() 方法,它返回一个Observable 检索与特定键匹配的最新ActionProfile

但是,我处理订阅者的方式让我感觉有些不妥。如果 Observable 的生命是无限的,你必须在 Observable 的构造之外自己管理订阅者,我是否正确? Observable 是否维护其订阅者列表?还是我有责任,所以我可以随时致电他们的onNext()

public final class ActionProfileManager {
    private final Observable<ImmutableMap<Integer,ActionProfile>> actionProfiles;
    private volatile ImmutableMap<Integer,ActionProfile> actionProfileMap;

    //do I really need this?
    private final CopyOnWriteArrayList<Subscriber<? super ImmutableMap<Integer,ActionProfile>>> subscribers = new CopyOnWriteArrayList<>();

    private ActionProfileManager() {
        this.actionProfiles = Observable.create(subscriber -> {
            subscriber.onNext(actionProfileMap);
            subscribers.add(subscriber); // is it up to me to capture the subscriber here or is it already saved somewhere for me?
        });
    }

    public void refresh() { 
        actionProfileMap = importFromDb();
        subscribers.forEach(s -> s.onNext(actionProfileMap));
    }

    public Observable<ActionProfile> forKey(int actionProfileId) { 
        return actionProfiles.map(m -> m.get(actionProfileId));
    } 
    private ImmutableMap<Integer,ActionProfile> importFromDb() { 
        return ImmutableMap.of(); //import data here
    }
}

【问题讨论】:

标签: java monads reactive-programming rx-java


【解决方案1】:

Cold Observable 通常一次与单个订阅者交互,即使您订阅了更多,它们也会独立运行,并且不需要相互了解。

另一方面,主题必须在他们自己收到的多播事件时跟踪他们的订阅者。

快速查看您的代码表明存在一些竞争条件和丢失通知的可能性。取而代之的是,您可以依赖 BehaviorSubject 这是异步字的“反应性属性”。让它存储当前的不可变映射并处理订阅者:

BehaviorSubject<ImmutableMap> bs = BehaviorSubject.create();
Subject<ImmutableMap, ImmutableMap> sync = bs.toSerialized();

forKey(k): bs.map(m -> m.get(k));

refresh(): sync.onNext(importFromDb());

【讨论】:

  • 我怀疑可能存在竞争条件。那么为什么人们经常说科目几乎不应该被使用呢?出于我的目的以及您所展示的内容,它们在某些情况下似乎是合适的。
  • 这种“不要使用”的说法对我来说总是很苛刻。我想说你应该首先寻找其他方式,但是有一些预期的使用意味着几乎立即使用主题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多