RxJava: Single, Maybe and Completable
Jan 11, 2018 · 2 min read
RxJava2 introduces different types of Observables : Flowable, Single, Maybe and Completable. We’ll be looking into Single, Maybe and Completable in brief.
Observable can emit multiple items
Single, Maybe and Completable are one or no emission of items.
Single
Single is an Observable which only emits one item or throws an error. Single emits only one value and applying some of the operator makes no sense. Like we don’t want to take value and collect it to a list.
Method onNext() and onComplete() of Observable has been combined to onSucess(), as the stream has only one single item to emit.
S i ngle is like promise in Javascript. A promise is an object that may produce a item or throw an error.
Typically example is a network call, with retrofit you return an Observable or Flowable. You usually care for the response once you can replace this with Single .
How you implement is
There are operators that will allow you to turn it into an Observable such as toObservable()
Maybe
Maybe is similar to Single only difference being that it allows for no emissions as well.
We will see example how to implement this
As we run the above code snippet
Item received: from singleSource single item
Done from EmptySource would be printed.
Completable
Completable is only concerned with execution completion whether the task has reach to completion or some error has occurred.
As Completable only concern is completeness it does not have onNext() and onSucess() method.
Example: There are certain scenario where only concern in completion or error. Suppose we update any User model in the app and want to just notify the server about it. We don’t care about the response because app already has the latest object.
Call the ApiClient updateUser
Thanks for reading and if you like the article, remember to clap. Note that if you hold the clap button, you can leave more claps!
Источник
Посмотрим на rx.Single в RxJava?
Всем добрый день! А может у кого-то и не день, но главное, чтобы был добрый. В этой статье я собираюсь рассказать совсем чуть-чуть про такой класс в RxJava, как Single.
А чем Single отличается от Observable ?
Конечно, у него нет всех методов, которые есть у Observable. Subscriber у Single также отличается тем, что содержит только два метода, а не три. Думаю, что все отличия в плане реализации вы сможете найти в документации.
Ответ тут очевиден: Single (что можно даже и из названия понять) содержит только один элемент, в отличии от Observable.
Кто-то подумает и скажет
пффф, ну и что? А я буду использовать всегда Obsevable, пусть в нем будет только один элемент.
По-моему мнению, в этом ничего страшного нет, но есть ли какие-то минусы от такого использования?
- Если вы знаете, что вы будете работать только с одним элементом, то в использовании Observable нет нужды или, как говорят, overkill;
- Также нужно понимать, что Observable более тяжеловесный, чем Single (а поговаривают, что Single даже быстрее);
В single возможны две ситуации:
- одно значение
- exception
Тут важно понимать, чего вы пытаетесь добиться, или какая ваша политика? Если вы считаете, что пустой результат для вас это нормально, то, скорее всего, Single вам не подойдет, но если это не так, и вы знаете, что результат обязательно должен быть, то Single это то, что вам надо. Кстати, стоит отметить, что у Single нет метода empty(). Это я на всякий случай решил сообщить.
Да покажи наконец как использовать этот Single!
Обычный пример из жизни. Предположим, что у нас микросервисная архитектура (обожаю микросервисы).
Входные данные: у нас есть три микросервиса A,B,C.
A — orchestration service.
Задача: сделать запрос в сервис B и в C из микросервиса A и сагрегировать данные.
Ответ: конечно, можно сделать запрос в микросервис B, а потом в микросервис C и потом сагрегировать данные в микросервисе A, но тогда приходится ждать результаты из одного микросервиса, а потом с другого. Ух, как же это долго!
Но вспоминаем, что у нас есть rx.Single, ураа!
Запрос в микросервис B и запрос в микросервис С происходят независимо друг от друга, а микросервис A просто ждет результатов.
Источник
RxJava Ninja: Single, Maybe and Completable
This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).
In this article, we will talk about special types of Observables. They still follow the observable contract but they are specialized for a specific purpose.
Single is an observable that emits only a single item. The factory operators for Single is more or less similar with observables restricted to a single emission. The only noticeable difference is the observer definition. The SingleObserver class is defined below.
Notice that there is no more onNext and onComplete and a new notification onSuccess is defined. This makes sense because a Single only emits a single item, hence it can be interpreted as onNext and onComplete at the same time. Let’s see an example.
The example above creates a Single observable that emits hello . The onSuccess handler prints the item. The output will be
Now, why is there a need to define a new type for this? Well, the answer lies on the communication of intention. Using Single can communicate, effectively I might add, the nature of the observable. For example, if you need to perform a one time network request, you can create it using Single and users of this observable does not need to look at the implementation details to know what to expect from this observable. Also, some operators just only return a single item so it is easier to express them this way. An example is the first operator which return the first item in the stream, a default value if there are no item in the observable source.
If there is a need for you to convert a Single to Observable , say for example you want to be notified on both onNext and onComplete , there is an operator just for that. You can use the toObservable . The opposite is also possible. singleOrError converts your Observable to a Single and if there are more than 1 item in the sequence, an exception will be thrown in the onError channel.
Maybe is similar to Single but this time, it allows your observable the ability to not emit any item at all. The MaybeObserver is defined as follows.
There are 4 notifications again, the onComplete is back (to signify no items) and the onSuccess as a combination of onNext and onComplete .
The sample code above will output
The first one emits onComplete because no there is nothing to emit. The second one outputs the hello under the onSuccess channel and does not emit an onComplete after. Maybe is also used in many operators to also communicate intention. For example, the first operator requires you to pass a default value in case there is no item. But you can specify it as a Maybe since it can either be an observable with a single item, or no items at all. This is what firstElement does.
Same with Single , Maybe can also be converted to Observable via the toObservable operator. Unfortunately, there is no straightforward way to convert an Observable to Maybe (unless you are interested in just the firstElement ). You can convert it to Single first though and then to Maybe using toMaybe .
This observable is only concerned about two things, if some action is executed or an error is encountered. Let’s check the definition of its observer.
There are only 2 events, onComplete and onError . This is useful for cases wherein you are only interested if something has executed properly, ignoring output or whatever.
Like the two above, Completable can be converted to an observable using toObservable . However, the reverse is also not straightforward. You can convert to a Single first and use ignoreElement , though if you want ( toCompletable is deprecated).
That’s it for special observables. Next, we will discuss hot vs. cold observables.
Источник
Combining Observables
Clone this wiki locally
This section explains operators you can use to combine multiple Observables.
Available in: Flowable ,
Observable ,
Maybe ,
Single ,
Completable
Emit a specified sequence of items before beginning to emit the items from the Observable.
Combines multiple Observables into one.
Available in: Flowable ,
Observable ,
Maybe ,
Single ,
Completable
Combines multiple Observables into one. Any onError notifications passed from any of the source observables will immediately be passed through to through to the observers and will terminate the merged Observable .
Available in: Flowable ,
Observable ,
Maybe ,
Single ,
Completable
Combines multiple Observables into one. Any onError notifications passed from any of the source observables will be withheld until all merged Observables complete, and only then will be passed along to the observers.
Available in: Flowable ,
Observable ,
Maybe ,
Single ,
Completable
Combines sets of items emitted by two or more Observables together via a specified function and emit items based on the results of this function.
Available in: Flowable ,
Observable ,
Maybe ,
Single ,
Completable
When an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function.
Available in: Flowable ,
Observable ,
Maybe ,
Single ,
Completable
Convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently emitted of those Observables.
- join( ) and groupJoin( ) — combine the items emitted by two Observables whenever one item from one Observable falls within a window of duration specified by an item emitted by the other Observable
- ( rxjava-joins ) and( ) , then( ) , and when( ) — combine sets of items emitted by two or more Observables by means of Pattern and Plan intermediaries
( rxjava-joins ) — indicates that this operator is currently part of the optional rxjava-joins package under rxjava-contrib and is not included with the standard RxJava set of operators
Copyright (c) 2016-present, RxJava Contributors.
Twitter @RxJava | Gitter @RxJava
Источник