8 Quick Ways To Create Observables
Many operators are available in RxJava to create observables. In this post I will go through each of them with examples. In the context of reactive programming, operator is nothing but a function which performs some operation, there are many types of operators available like creation, transforming, filtering, error handling, combining and many more. Lets go with each static create operator supported by RxJava.
Interval
Generate’s sequence of numbers starting from 0 with some delay. Code shown below will wait for two seconds before generating numbers and then for each generated number it takes one second.
<1> Subscriber prints the values to console.
<2> Note that subscriber listens for the values in a different thread. If the main thread completes its execution then the program terminates so to we are making main thread to sleep for 10 seconds. Mean while subscriber prints nine values.
Just
This operator generates the values which are passed as arguments.
<1> There are many just methods which can handle up to ten parameters. In this example it takes four parameters.
<2> subscribe method takes three parameters method which takes:
- Consumer, to process value
- Consumer, to process error notification
- Action, to process complete notification
From
This operator can generate values from difference sources like array, collections, iterable, callable and futures.
<1> fromArray take variable arguments.
<2> fromIterable takes any Iterable collection, here I passed List.
Timer
Generate zero after specified delay.
Empty / Never / Error
Empty does not emit any value and terminates normally.
Never will not emit any value and does not terminate.
Throw does not emit any values but terminates with an error.
Range
Emits range of sequence numbers. Below code generates 5 numbers starting from 10.
Conclusion
We went through different operators to generate values for the subscribers.