Exploring RXJava in Android — Different types of Observables
This article is part of RxJava Introduction series. You can checkout the entire series here:
- RxJava Introduction and Operators for creating Observables
- RxJava Operators: Operators for Transforming Observables
- RxJava Operators: Operators for Filtering Observables
- RxJava Operators: Operators for Combining Observables
- RxJava Operators: Utility Operators
- RxJava Operators: Conditional and Boolean Operators
- RxJava Operators: Mathematical and Aggregate Operators
- RxJava: Different types of Observables — You are here
- RxJava: Different types of Subjects
Different Types of Observables
Single
Single is an Observable that always emit only one value or throws an error. A typical use case of Single observable would be when we make a network call in Android and receive a response.
Sample Implementation: The below code always emits a Single user object. We use a Single Observable and a Single Observer. The Single Observer always emits only once so there is no onNext()
.
Output
User with name 'Anitaa' successfully created
Maybe
Maybe is an Observable that may or may not emit a value. For example, we would like to know if a particular user exists in our db. The user may or may not exist.
Sample Implementation: The below code mimics a scenario where a user object is emitted. We use a Maybe Observable and a Maybe Observer. Again we are using the same scenario as above: creating a new User.
Completable
Completable does not emit any data, but rather is focused on the status of execution — whether successful or failure.
Sample Implementation: The below code mimics a scenario where an existing User object is updated. Since no data is emitted in Completable, there is no onNext()
or onSuccess()
. This scenario can be used in cases where PUT api is called and we need to update an existing object to the backend.
Output
onComplete is called
Flowable
Flowable is typically used when an Observable is emitting huge amounts of data but the Observer is not able to handle this data emission. This is known as Back Pressure.
Sample Implementation: The below sample provides a range of integers from 10 to 1000 and uses the reduce()
operator to add the sum of the integers and emit the final sum value.
Output
onSubscribe is called
Success: 509501
You can checkout a lot more about Flowable operators from here.
That’s it guys! This is part eight of the series on RxJava. I hope you enjoyed this article and found it useful, if so please hit the Clap button. Let me know your thoughts in the comments section.
Happy coding!