![](/img/trans.png)
[英]RxJava- CombineLatest but only fire for one Observable's emission?
[英]RxJava- No access to Observable's subscribers?
我知道在反應式編程中使用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
}
}
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.