Creating an observable from a single value

When composing multiple observables or mocking observables for testing purposes, you might need to create an observable that would emit only one value and then terminate itself. RxJS has two methods to implement this behavior: the return() method and the just() method. They work exactly in the same way and have the following signature:

Rx.Observable.return(value, [scheduler]); Rx.Observable.just(value, [scheduler]); 

The first argument is mandatory and the second is optional:

  • value: This can be any object; it is the value to be emitted on the sequence
  • scheduler: This is used to emit the value

The following code illustrates an example of this method:

Rx.Observable     .just('Hello World')  .subscribe((i)=> ...

Get Mastering Reactive JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.