【发布时间】: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
}
}
【问题讨论】:
-
我没有足够的经验来回答你的问题,但是:1.) 你可能会发现我在 CR 上的问题的答案很有趣:codereview.stackexchange.com/a/90090/68342 2.) 你可能想看看在源代码 sqlbrite,特别是这个文件,它在内部使用
Subject来处理重新加载/触发器:github.com/square/sqlbrite/blob/master/sqlbrite/src/main/java/…
标签: java monads reactive-programming rx-java