RxJava: Single, Maybe and Completable

Tram Ho

RxJava2 introduces many different types of Observable: Flowable, Single, Maybe and Completable. Today we will briefly learn Single, Maybe and Completable.

Observable can emit many items.

Single, Maybe and Completable may not or emit many items.

Single

Single is a variation of Observable. It will only emit an item if it succeeds or throws an error. The singles only emit a value and some operators have no effect when used with it.

Observable’s onNext() and onComplete() methods have been combined into the onSucess() .

Single is like promise in Javascript. Promises are objects that only create an item or throw an error.

Typical example is when calling network. With Retrofit you are returned to Observable or Flowable. If you only care about returned data then you can use Single<T> instead.

Here is the implementation:

You can also convert it into a Observable with operator: toObservable()

Maybe

Maybe is similar to Single, except that it allows no items to be emit.

We will look down the example below to see how to implement:

Running the code above, we will get the following result:

Completable

Completables only care about whether or not the execution has been completed or an error has occurred. Regardless of the result returned.

Completable only takes care of its completion so it doesn’t have onNext() and onSucess()

For example: Here we have cases that only care about completion or error. Suppose we update the user’s information to the server. And just want to receive a notification of return. We do not need to return the user just now because the app already has that object.

Call ApiClient updateUser:

Recently I gave a brief presentation on how to use: Single , Maybe , Completable . Thank you for taking the time to read. Happy coding !!! 😁

The article is available at: https://android.jlelse.eu/rxjava-single-maybe-and-completable-8686db42bac8

Share the news now

Source : Viblo