我有以下代码。为什么虽然 Flux 从 Publisher 扩展而来,但我不能在发布者的 subscribe 方法上使用 lambda,而可以在 Flux 上使用?
Publisher<String> publisher = new Publisher<String>() {
@Override
public void subscribe(Subscriber<? super String> subscriber) {
subscriber.onNext("Hello world");
subscriber.onNext("Hello world");
subscriber.onNext("Hello world");
subscriber.onNext("Hello world");
subscriber.onComplete();
}
};
//this lines gives me an error "Subscriber<String> is not a functional interface"
publisher.subscribe(System.out::println);
//no error on this line
Flux.just("a","b","c","d")
.subscribe(System.out::println);
最佳答案
Publisher.subscribe
采用 Subscriber
作为参数,这不是一个函数式接口(interface)。
Flux
有一个重载的 subscribe
方法,该方法采用 Consumer
作为参数,这是一个函数式接口(interface)。事实上,您在最后一行中使用的是后一个版本。
参见Javadoc
关于java - 订阅者不是一个函数式接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59013907/