假设我有一个事件总线:
public class MessageEventBus {
private static MessageEventBus INSTANCE;
private PublishSubject<Message> bus = PublishSubject.create();
private MessageEventBus() {};
public static MessageEventBus instance() {
if (INSTANCE == null) {
INSTANCE = new MessageEventBus();
}
return INSTANCE;
}
public void send(Message message) {
bus.onNext(message);
}
public Observable<Message> toObservable() {
return bus;
}
public boolean hasObservers() {
return bus.hasObservers();
}
}
在Android服务中,事件被推送到总线:
MessageEventBus bus = MessageEventBus.instance();
Message message = new Message(userId, text);
if (bus.hasObservers()) {
bus.send(message);
return;
}
在MVP演示者中,这是我将观察者附加到事件总线上的要点:
MessageEventBus bus = MessageEventBus.instance();
bus.toObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(message -> {
if (message.userId == userId) {
view.messageReceived(message);
}
});
如何将if (message.userId == userId)
支票从演示者转移到服务?还是将检查移到事件总线本身?服务中的伪代码如下:
MessageEventBus bus = MessageEventBus.instance();
Message message = new Message(userId, text);
if (bus.hasObservers() && message.userId == theUserIdInThePresenter) {
bus.send(message);
}
或者换句话说,在实际发出该可观察对象之前,如何检查观察者是否符合某些条件?
答案 0 :(得分:2)
在Observer-Observable模式中,Obsrvables不应关心订阅它们的观察者。 它们的目的是发出数据。 但是,您可以使用filter operator以更优雅的方式进行过滤。您有两种可能性:
1-将过滤器放入Presenter中
MessageEventBus bus = MessageEventBus.instance();
bus.toObservable()
.filter(message.userId == userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(message -> {
//you will only received message which match id
});
2-将过滤器放入服务内部
public class MessageEventBus {
private static MessageEventBus INSTANCE;
private PublishSubject<Message> bus = PublishSubject.create();
private MessageEventBus() {};
public static MessageEventBus instance() {
if (INSTANCE == null) {
INSTANCE = new MessageEventBus();
}
return INSTANCE;
}
public void send(Message message) {
bus.onNext(message);
}
//filter here
public Observable<Message> toFilteredObservable(int userId) {
return bus
.filter(message -> message.userId == userId)
;
}
public Observable<Message> toObservable() {
return bus;
}
public boolean hasObservers() {
return bus.hasObservers();
}
}
并在主持人内部这样调用:
bus.toFilteredObservable(int userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(message -> {
});
PS:如果您希望观察者遵守观察者标准,则应手动实施该模式。