Spring 5.0 Projects
上QQ阅读APP看书,第一时间看更新

Other ways to get Observable

So far we have seen how to get Observable with just(), create(), and interval(). However, there are other sources to get the Observable. You can get full details about each source from at:https://github.com/ReactiveX/RxJava/wiki/Creating-Observables:

  1. range: If you want to emit a consecutive range of integers, you can use the Observable.range(int from, int to) call. As its name suggests, it will start emitting a number from the start value in increments until the end count is reached.
  2. empty: In a rare situation, you need to create Observable that emits nothing and calls onComplete(). In this case, you can use this source type with the Observable.empty() call. 
  3. never: It is equivalent to empty with the difference being that this will never make a call to onComplete() and keep the Observable waiting to emit a state. This is also used less frequently. 
  4. error: If you wish to create Observable that immediately calls onError(), you can use this source with the Observable.error() call. It is used for testing purposes mainly.
  5. future: It was introduced way back and used as a placeholder for the result that is not yet produced. Observable is more powerful than future but if you are using old libraries, you can convert Observable to future with the Observable.future() call.
  6. defer: This is basically used to create a separate state for each Observer. It is useful when the source of the stream is stateful. If you want your observers to reflect the changes happening to the  Observable state, then you can use this source type with an Observable.defer() call.
  7. single: This type of Observable just emits a single value and can be used with a Single.just() method call.
  8. maybe: It is similar to the single type, the only difference that it emits zero or one data at maximum and can be used with a Maybe.just() call.
  9. fromCallable: If you want to perform certain actions of computation before emitting the data, you can use this source with an Observable.fromCallable() call. In case any error occurs and you want to pass it to the Observable chain through an onError() call instead of throwing the error, you can use this source type.