我正试图在register方法中使用过滤创建一个热可观察对象,作为实现如下基本接口的事件列表:
public void register(Observer<AppEvent> observer, List<AppEvent> filter) {
Log.d(TAG, "Registering observer");
subject.subscribeOn(Schedulers.io())
.filter(o -> {
return filter.stream().anyMatch(it -> (o instanceof it));
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
public interface AppEvent extends Serializable {
}
public static class ItemDetails implements AppEvent {
public String info;
public ItemDetails(String malwareInfo) {
info = malwareInfo;
}
}
public static class InitApi implements AppEvent {
public Boolean isSuccess;
public InitApi(boolean isSuccess) {
this.isSuccess = isSuccess;
}
}
我想做的是根据事件类的类型,在我们的例子中是ItemDetails或InitApi,创建一个过滤器。从逻辑上讲,代码是正确的:
.filter(o -> {
return filter.stream().anyMatch(it -> (o instanceof it));
})
但是编译器说CCD_ 1。
如何对AppEvent列表进行筛选?
如注释中所述,您会看到编译器错误,因为instanceof
运算符要求右侧参数为类或接口。
如果你试图创建一个";允许的";要传递给Observer
的事件列表,您可以执行以下操作:
public void register(Observer<AppEvent> observer, List<AppEvent> filter) {
Log.d(TAG, "Registering observer");
// Collect the names of events to pass on to the observer
final List<String> allowedEventNames = filter.stream()
.map(it -> it.getClass().getName())
.collect(Collectors.toList());
subject.subscribeOn(Schedulers.io())
// Filter based on names
.filter(event -> allowedEventNames.contains(event.getClass().getName()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}