Java 观察者和订阅者有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27664221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:48:41  来源:igfitidea点击:

What is the difference between an Observer and a Subscriber?

javarx-java

提问by MarcusH

I am trying to decipher the following function:

我正在尝试破译以下功能:

Subscription getCar(id, Observer<Car> observer) {
    return getCarDetails(id, new Observer<CarDetails> {
                             @Override
                             onNext(CarDetails details) {           
                                 observer.onNext(details.getCar());
                             } });
}

I got a good intro to rxjava from http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/but it only mentioned Observer in passing, saying you'll be using Subscriber most of the time to consumer items emitted from an Observable.

我从http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/得到了一个很好的 rxjava 介绍,但它只是顺便提到了观察者,说你将使用订阅者大部分从 Observable 发出的消费项目的时间。

Can someone explain to me

谁能给我解释一下

  1. What is an observer?
  2. How is an observer different than a subscriber?
  3. What does the above code snippet do?
  1. 什么是观察者?
  2. 观察者与订阅者有何不同?
  3. 上面的代码片段有什么作用?

Javadocmade it seem just like a subscriber. The javadoc for subscriber says it implements observer and subscription. I am very confused.

Javadoc使它看起来就像一个订阅者。订阅者的 javadoc 说它实现了观察者和订阅。我很困扰。

采纳答案by Brice

EDITED: with @Alrid's comment

编辑:@Alrid 的评论

tl;dr

tl;博士

public abstract class Subscriber<T> implements Observer<T>, Subscription

So a Subscriberis an implementation of the Observer, with additional semantics on subscription (it's more about un-subscription). The code in your question just shows that it passes the Observerinterface, instead of the implementation (usual programming practice).

所以SubscriberObserver 的一个实现,在订阅上有额外的语义(更多的是关于取消订阅)。您问题中的代码只是表明它通过了Observer接口,而不是实现(通常的编程实践)。

Also this code returns a Subscription, that may be because the author of this code thought that the client should only have access to Subscriptionmethods, without access to elements produced by the observable. That may be a programmer error.

这段代码也返回一个Subscription,这可能是因为这段代码的作者认为客户端应该只能访问Subscription方法,而不能访问由 observable 生成的元素。那可能是程序员的错误。

long story

很长的故事

Really you should read the content of this website (or book) : http://www.introtorx.comIt is about Rx.Net, but the concepts are the very same, they were created by Erik Meijer and RxJava implementors followed them(if applicable to the Java language).

真的你应该阅读这个网站(或书)的内容:http: //www.introtorx.com它是关于 Rx.Net,但概念是非常相同的,它们是由 Erik Meijer 创建的,并且 RxJava 实现者跟随他们(如果适用于 Java 语言)。

This page will interest you (it is the second chapter) : KeyTypes

这个页面会让你感兴趣(这是第二章):KeyTypes

Here you'll read in the first paragraphs :

在这里,您将阅读第一段:

There are two key types to understand when working with Rx, and a subset of auxiliary types that will help you to learn Rx more effectively. The IObserver and IObservable form the fundamental building blocks for Rx, while implementations of ISubject reduce the learning curve for developers new to Rx.

使用 Rx 时需要了解两种关键类型,以及帮助您更有效地学习 Rx 的辅助类型子集。IObserver 和 IObservable 构成了 Rx 的基本构建块,而 ISubject 的实现减少了 Rx 新开发人员的学习曲线。

...

...

Essentially Rx is built upon the foundations of the Observer pattern. .NET already exposes some other ways to implement the Observer pattern such as multicast delegates or events (which are usually multicast delegates).

本质上,Rx 建立在观察者模式的基础上。.NET 已经公开了一些其他方法来实现观察者模式,例如多播委托或事件(通常是多播委托)。

Even if types / API are a bit different, you will learn a lot with this book, probably way more than with some blogs.

即使类型/API 有点不同,你也会从这本书中学到很多东西,可能比阅读一些博客要多得多。

What this bookdo not say(...because it is in the RxJava implementation)

本书没有说的...因为它在 RxJava 实现中

RxJava main developer at this time introduced a slight variation (see PR #792) that allowed to distinguish two types of contracts :

RxJava 的主要开发人员此时引入了一个细微的变化(参见 PR #792),它允许区分两种类型的合同:

  • notification -> Observer
  • (un)subscription -> Subscription
  • 通知 -> Observer
  • (取消)订阅 -> Subscription

This change allowed to better express/split these concerns of the implementing classes of the RxJava library.

这种变化允许更好地表达/拆分 RxJava 库的实现类的这些关注点。

However as a library user, using actual implementations of the RxJava library should be good enough.

然而,作为一个库用户,使用 RxJava 库的实际实现应该就足够了。

Implementing a subscriber require much more knowledge, work and care, indeed the subscription semantics are very important depending on the type of the source observable (Hot or cold? Expensive to create ?)

实现订阅者需要更多的知识、工作和关怀,确实订阅语义非常重要,具体取决于源可观察的类型(热或冷?创建昂贵?)



Exposing Subscriberrather than Observerin cases such as above will not interfere with the code in in most cases, but it is not the intended use for it unless those un-subscription semantics are needed. But in the end implementing a Subscriber, and may involve to fall in some pitfalls such as :

在大多数情况下,公开Subscriber而不是Observer在上述情况下不会干扰代码,但除非需要那些取消订阅语义,否则它不是它的预期用途。但最终实现 a Subscriber,并且可能会陷入一些陷阱,例如:

  1. spend resources for functionality you will not use
  2. cannot inherit from another class
  3. write incorrect un-subscription code
  4. copy/paste code an incorrect code or correct code written for a different context
  1. 将资源用于您不会使用的功能
  2. 不能从另一个类继承
  3. 写不正确的取消订阅代码
  4. 复制/粘贴代码 不正确的代码或为不同上下文编写的正确代码

回答by Lawrence Kesteloot

(Edit: This is apparently only true of RxJava 1.)

(编辑:这显然只适用于 RxJava 1。)

  1. An Observeris an object that can get data from a data source (an Observable). The data source pushes data to it by calling the observer's onNext().

  2. A Subscriberis an Observerthat can also unsubscribe from that data source (through the Subscriptioninterface).

  3. The getCar()function is trying to return cars, but there's no direct method to do that. But there is a function to get car details (getCarDetails()) which will call an observer with all the car details. So it calls that function and passes it an observer that, when it gets data, will fetch the car data from the details and pass it on to its own observer.

  1. AnObserver是可以从数据源 (an Observable)获取数据的对象。数据源通过调用观察者的onNext().

  2. ASubscriberObserver可以取消订阅该数据源(通过Subscription接口)。

  3. getCar()函数试图返回汽车,但没有直接的方法可以做到这一点。但是有一个函数可以获取汽车详细信息 ( getCarDetails()),它将调用具有所有汽车详细信息的观察者。因此它调用该函数并将其传递给一个观察者,当它获取数据时,将从详细信息中获取汽车数据并将其传递给它自己的观察者。

回答by Yaroslav Stavnichiy

In RxJava 2org.reactivestreams.Subscriberis an interface complying to Reactive Streams specification.

在 RxJava 2 中org.reactivestreams.Subscriber是一个符合Reactive Streams 规范的接口。

The main difference from Observableis that new Subscribersupports backpressure.

主要区别Observable在于新Subscriber支持背压。

Observeris subscribed to Observable, and Subscriberis subscribed to Flowable(implements org.reactivestreams.Publisher).

Observer已订阅Observable,并Subscriber已订阅Flowable(实现org.reactivestreams.Publisher)。

See detailed description here.

请参阅此处的详细说明。

回答by Beshoy Fayez

Also in RxJava2, if you want to be able to unsubscribe, you should use ResourceObserverfor Observableand ResourceSubscriberfor Flowable.

同样在RxJava2 中,如果您希望能够取消订阅,您应该使用ResourceObserverforObservableResourceSubscriberfor Flowable

Check this question

检查这个问题