【问题标题】:Hot observable with filters RX Java带有过滤器 RX Java 的热可观察
【发布时间】:2021-04-11 21:38:44
【问题描述】:

我正在尝试在 register 方法中使用 filtering 创建一个热可观察对象,作为实现基本接口的事件列表,如下所示:

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));
                })

但是编译器说unknown class it

如何过滤 AppEvent 列表?

【问题讨论】:

  • instanceof 的参数必须是类型的名称,即类或接口。 it 不是类或接口的名称。因此编译器错误 it is not a class

标签: java android filter rx-java


【解决方案1】:

正如 cmets 中所述,您会看到编译器错误,因为 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);
}

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2019-06-05
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多