rxjava 订阅对象
Rx stands for Reactive Extensions. RxJava
is an awesome reactive library that we can easily integrate into our applications.
Rx代表React式扩展。 RxJava
是一个很棒的React式库,我们可以轻松地将其集成到我们的应用程序中。
We can understand RxJava
as data emitted by one component, called Observable
, and the underlying structure provided by the Rx libraries will propagate changes to another component, Observer
. Simply put, it’s an API for asynchronous programming with observable streams.
我们可以将RxJava
理解为一个组件(称为Observable
发出的数据,Rx库提供的底层结构会将更改传播到另一个组件Observer
。 简而言之,它是用于具有可观察流的异步编程的API。
RxJava — Multi-Threading in Android helps to understand the basics of Rx, everything about Observable
s, Observer
s, Scheduler
s, etc. So, hoping that you already know about basics of RxJava
lets start by discussing Observable
.
RxJava -多线程在Android的帮助理解的Rx,一切有关的基础知识Observable
小号 , Observer
小号 , Scheduler
小号等,所以,希望你已经知道的基本知识RxJava
让通过讨论开始Observable
。
什么是可观察的? (What is an Observable?)
In RxJava
, Observable
s are the source that emits data to the Observers
. We can understand observable
s as suppliers — they process and supply data to other components. It does some work and emits some values.
在RxJava
, Observable
是向Observers
发出数据的源。 我们可以将observable
理解为供应商-他们处理数据并将数据提供给其他组件。 它完成一些工作并发出一些值。
The following are the different types of Observable
s in RxJava
以下是RxJava中不同类型的Observable
Observable
Observable
Flowable
Flowable
Single
Single
Maybe
Maybe
Completable
Completable
We’ll discuss each type in detail in the next post but just remember that there are different types of Observable
s for different purposes.
我们将在下一篇文章中详细讨论每种类型,但是请记住,出于不同目的,存在不同类型的Observable
。
There are many methods provided by the RxJava
library for Observabl
e creation. Let's look at these methods and understand when to use each method:
RxJava
库提供了许多创建Observabl
方法。 让我们看一下这些方法,并了解何时使用每种方法:
create()
create()
just()
just()
defer()
defer()
empty()
empty()
never()
never()
error()
error()
range()
range()
interval()
interval()
timer()
timer()
from()
from()
创造() (create())
Create an Observable
from scratch by means of a function:
通过一个函数从头创建一个Observable
:
val createObserver = Observable.create(ObservableOnSubscribe<String> { emitter ->emitter.onNext("Hello World")
emitter.onComplete()})
The create factory method is the preferred way to implement custom observable sequences. Essentially, this method allows you to specify a delegate that will be executed every time a subscription is made.
创建工厂方法是实现自定义可观察序列的首选方法。 本质上,此方法使您可以指定将在每次进行预订时执行的委托。
Note: Flowable.create()
must also specify the backpressure behavior to be applied when the user-provided function generates more items than the downstream consumer has requested.
注意: Flowable.create()
还必须指定 当用户提供的功能生成的商品数量超过下游消费者要求的数量时要应用 的 背压 行为。
ObservableOnSubscribe
is a functional interface that has a subscribe()
method that receives an instance of an ObservableEmitter
instance that allows pushing events in a cancellation-safe manner. Have a look at the interface:
ObservableOnSubscribe
是一个功能接口,具有一个subscribe()
方法,该方法接收ObservableEmitter
实例的实例,该实例允许以取消安全的方式推送事件。 看一下界面:
/* @param <T> the value type pushed
*/public interface ObservableOnSubscribe<T> {/**
* Called for each Observer that subscribes.
* @param emitter the safe emitter instance, never null
* @throws Exception on error
*/void subscribe(@NonNull ObservableEmitter<T> emitter) throws Exception;
}
只是() (just())
This is one of the easiest and convenient ways to create observable. just()
constructs a reactive type by taking a pre-existing object and emitting that specific object to the downstream consumer upon subscription. The just operator converts an item into an Observable
that emits that item.
这是创建可观察的最简单便捷的方法之一。 just()
通过获取一个预先存在的对象并在订阅时将该特定对象发送给下游使用者来构造一个React类型。 正义运算符将项目转换为发出该项目的Observable
。
val justObservable = Observable.just(4, 5, 6, null)
Remember that if you pass null
to Just
, it will return an Observable
that emits null
as an item. Don’t make the mistake of assuming this will return an empty Observable
to Just
— it will return an Observable
that emits null
as an item.
请记住,如果将null
传递给Just
,它将返回一个Observable
,该对象将null
发射为项。 不要误以为这将返回一个空的Observable
到Just
它会返回一个Observable
,该Observable
作为项目发出null
。
Observable.just()
emits whatever is present inside the just function. It can take between two and nine parameters. If you pass a list or array in just()
it will emit the list or array only.
Observable.just()
发出just函数中存在的任何内容。 它可以使用两个到九个参数。 如果您在 just()
传递列表或数组, 它将仅发出列表或数组。
延迟 () (defer())
defer()
does not create the Observable
until the observer subscribes and creates a fresh Observable
for each observer
. The Defer
operator waits until an observer subscribes to it, then it generates an Observable
, typically with an Observable
factory function. It does this creation for each subscriber
— although each subscriber
may think it’s subscribing to the same Observable
, in fact, each subscriber gets its own individual sequence.
defer()
不创建Observable
到的观察者订阅,并创建一个新的Observable
每个observer
。 Defer
运算符等待观察者订阅它,然后生成一个Observable
,通常带有Observable
工厂函数。 它为每个subscriber
执行此创建操作-尽管每个subscriber
可能认为它正在订阅相同的Observable
,但实际上,每个订阅者都有自己的单独序列。
val observable = Observable.defer {val time = System.currentTimeMillis()
Observable.just(time)}
In some circumstances, waiting until the last minute (that is, until subscription time) to generate the Observable
can ensure it contains the latest data.
在某些情况下,等到最后一分钟(即直到订阅时间)生成Observable
才能确保它包含最新数据。
空() (empty())
empty()
creates an Observable
that emits no items to but terminates normally. This type of source signals completion immediately upon subscription. It returns an Observable
that emits no items to the Observer
and immediately invokes its onComplete()
method.
empty()
创建一个Observable
,该对象不向其发射任何物品,但通常会终止 。 这种类型的信号源在订阅后立即发出完成信号。 它返回一个Observable
,它不向Observer
发射任何项目,并立即调用其onComplete()
方法。
val empty = Observable.empty()
empty.subscribe({ v -> println("This should never be printed!") },{ error -> println("Or this!") },{ println("Done will be printed.") })
决不() (never())
never()
Creates an Observable
that emits no items and does not terminate. This type of source does not signal any onNext
, onSuccess
, onError
or onComplete
. This type of reactive source is useful for testing or disabling certain sources in combinator operators.
never()
创建一个Observable
不发射任何物品,也不会终止。 这种类型的源不表示任何onNext
, onSuccess
, onError
或onComplete
。 这种类型的无功信号源可用于测试或禁用组合器运算符中的某些信号源。
val never = Observable.never()
never.subscribe({ v -> println("This should never be printed!") },{ error -> println("Or this!") },{ println("This neither!") })
错误() (error())
error()
signals an error, either pre-existing or generated via a java.util.concurrent.Callable
, to the consumer.
error()
向使用者发出一个错误,该错误是预先存在的或通过java.util.concurrent.Callable
生成的。
val error = Observable.error(IOException())
error.subscribe({ v -> println("This should never be printed!") },{ e -> e.printStackTrace() },{ println("This neither!") })
onErrorResumeNext()
instructs an ObservableSource
to pass control to another ObservableSource
, rather than invoking Observer.onError()
, if it encounters an error in a chain of sequence.
onErrorResumeNext()
指示ObservableSource
在序列链中遇到错误时,将控制权传递给另一个ObservableSource
,而不是调用Observer.onError()
。
If you pass another ObservableSource
resume sequence to an ObservableSource
’s onErrorResumeNext()
method, if the original ObservableSource
encounters an error, instead of invoking its Observer
’s onError()
method, it will relinquish control to resume sequence which will invoke the Observer
’s onNext()
method if it is able to do so. In such a case, the Observer
may never know that an error has occurred. You can use this to prevent errors from propagating or to supply fallback data should errors be encountered.
如果您将另一个ObservableSource
恢复序列传递给ObservableSource
的onErrorResumeNext()
方法,则如果原始ObservableSource
遇到错误,则将放弃控制权以恢复序列 ,而不是调用其Observer
的onError()
方法,该序列将调用Observer
' s onNext()
方法(如果可以)。 在这种情况下, Observer
可能永远不知道发生了错误。 您可以使用它来防止错误传播或在遇到错误时提供备用数据。
val observable = Observable.fromCallable {if (Math.random() < 0.5) {
throw IOException()
}
throw IllegalArgumentException()}val result = observable.onErrorResumeNext { error ->if (error is IllegalArgumentException) {
return@onErrorResumeNext Observable.empty()
}
Observable.error(error)}for (i in 0..9) {
result.subscribe({ v -> println("This should never be printed!") },{ error -> error.printStackTrace() },{ println("Done") })
}
范围() (range())
range()
creates an Observable
that emits a particular range of sequential integers. The Range
operator emits a range of sequential integers in order, where you select the start of the range and its length. It generates a sequence of values for each individual consumer. The range()
method generates Integer
s, the rangeLong()
generates Long
s.
range()
创建一个Observable
,它发出特定范围的连续整数。 Range
运算符按顺序发出一系列连续整数,您可以在其中选择范围的起点及其长度。 它为每个消费者生成一系列值。 range()
方法生成Integer
, rangeLong()
生成Long
。
val greeting = "Hello World!"
val indexes = Observable.range(0, greeting.length)
val characters = indexes
.map { index -> greeting[index] }characters.subscribe({ character -> print(character) }, { error -> error.printStackTrace() },{ println() })
间隔() (interval())
interval()
creates an Observable
that emits a sequence of integers spaced by a given time interval. The Interval
operator returns an Observable
that emits an infinite sequence of ascending integers, with a constant interval of time of your choosing between emissions.
interval()
创建一个Observable
,它发出以给定时间间隔隔开的整数序列。 Interval
运算符返回一个Observable
,该Observable
发射无限个递增整数序列,并在发射之间选择固定的时间间隔。
val clock = Observable.interval(1, TimeUnit.SECONDS)
clock.subscribe { time ->if (time!! % 2 == 0L) {println("Tick")
} else {println("Tock")
}}
定时器() (timer())
timer()
creates an Observable
that emits a particular item after a given delay that we specify.
timer()
创建一个Observable
,该Observable
在我们指定的给定延迟后发出特定项目。
val eggTimer = Observable.timer(5, TimeUnit.MINUTES)
eggTimer.blockingSubscribe { v -> println("Egg is ready!") }
从 (from)
from
is used to convert various other objects and data types into Observable
s. When we work with Observable
s, it can be more convenient if all the data you mean to work with can be represented as Observable
s, rather than as a mixture of Observable
s and other types. This allows you to use a single set of operators to govern the entire lifespan of the data stream.
from
用于将其他各种对象和数据类型转换为Observable
。 当我们使用Observable
,如果您要使用的所有数据都可以表示为Observable
,而不是Observable
和其他类型的混合,则可以更加方便。 这使您可以使用一组运算符来控制数据流的整个生命周期。
fromIterable() (fromIterable())
fromIterable()
signals the items from a java.lang.Iterable
source (such as List
s, Set
s or Collection
s or custom Iterable
s) and then completes the sequence. Converts an Iterable
sequence into an ObservableSource
that emits the items in the sequence.
fromIterable()
对来自java.lang.Iterable
源(例如List
, Set
或Collection
或custom Iterable
fromIterable()
的项目发出信号,然后完成序列。 将Iterable
序列转换为ObservableSource
,以发出序列中的项。
val numbers = ArrayList<Int>()
numbers.add(1)
numbers.add(2)
numbers.add(3)
numbers.add(4)
val fromObservable = Observable.fromIterable(numbers)
fromArray() (fromArray())
fromArray()
converts an Array
into an ObservableSource
that emits the items in the Array
.
fromArray()
将Array
转换为ObservableSource
,它发出Array
的项目。
val observable = Observable.fromArray(array)
observable.subscribe({ item -> println(item) }, { error -> error.printStackTrace() },{ println("Done") })
Note: RxJava does not support primitive arrays, only (generic) reference arrays.
注意 :RxJava不支持基本数组,仅支持(通用)引用数组。
fromCallable() (fromCallable())
When a consumer subscribes, the given java.util.concurrent.Callable
is invoked and its returned value (or thrown exception) is relayed to that consumer.
使用者订阅时,将调用给定的java.util.concurrent.Callable
并将其返回值(或引发的异常)中继到该使用者。
In other words, it returns an Observable
that, when an observer subscribes to it, invokes a function you specify and then emits the value returned from that function. This allows you to defer the execution of the function you specify until an observer subscribes to the ObservableSource
. That’s to say, it makes the function “lazy.”
换句话说,它返回一个Observable
,当观察者订阅它时,它调用您指定的函数,然后发出从该函数返回的值。 这样,您可以将指定的功能的执行推迟到观察者订阅ObservableSource
。 也就是说,它使函数“懒惰”。
val callable = Callable {println("Hello World!")
return@Callable ("Hello World!")}val observable = Observable.fromCallable(callable)
observable.subscribe({ item -> println(item) }, { error -> error.printStackTrace() },{ println("Done") })
fromAction() (fromAction())
fromAction()
returns a Completable
instance that runs the given Action
for each subscriber and emits either an unchecked exception or simply completes.
fromAction()
返回一个Completable
实例,该实例为每个订阅者运行给定的Action
,并发出未经检查的异常或只是完成。
val action = Action{ println("Hello World!") }val completable = Completable.fromAction(action)
completable.subscribe({ println("Done") }, { error -> error.printStackTrace() })
fromRunnable() (fromRunnable())
fromRunnable()
returns a Completable
instance that subscribes to the given Observable, ignores all values and emits only the terminal event.
fromRunnable()
返回一个Completable
实例,该实例订阅给定的Observable,忽略所有值并仅发出终端事件。
val runnable = { println("Hello World!") }val completable1 = Completable.fromRunnable(runnable)
completable.subscribe({ println("Done") },{ error -> error.printStackTrace() })
Note: The difference between fromAction
and fromRunnable
is that the Action
interface allows throwing a checked exception while the java.lang.Runnable
does not.
注意 : fromAction
和 fromRunnable
之间的区别在于 , Action
接口允许 fromRunnable
检查的异常,而 java.lang.Runnable
不允许。
fromFuture() (fromFuture())
fromFuture()
converts a java.util.concurrent.Future
into an ObservableSource
. We can convert any object that supports the Future
interface into an ObservableSource
that emits the return value of the Future.get()
method of that object, by passing the object into the from()
method.
fromFuture()
转换java.util.concurrent.Future
到一个ObservableSource
。 我们可以转换支持任何对象Future
接口成ObservableSource
发射所述的返回值Future.get()
该对象的方法,通过将对象插入到from()
方法。
val executor = Executors.newSingleThreadScheduledExecutor()
val future = executor.schedule({ "Hello world!" }, 1, TimeUnit.SECONDS)
val observable = Observable.fromFuture<String>(future)
observable.subscribe({ item -> println(item) },{ error -> error.printStackTrace() },{ println("Done") })
That’s not everything there is to know about Observables — there’s much more.
并不是有关Observables的所有信息,而是更多。
奖金 (Bonus)
Eager to learn more about Rx please continue your reading on the Series Complete Guide on RxJava.
Please let me know your suggestions and comments. Thank you for reading.
请让我知道您的建议和意见。 感谢您的阅读。
翻译自: https://medium.com/better-programming/rxjava-different-ways-of-creating-observables-7ec3204f1e23
rxjava 订阅对象