O'Reilly logo

Mastering Reactive JavaScript by Erich de Souza Oliveira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating an observable from a factory function

There is a method in RxJS where you can create an observable from a function that returns an observable or an observable factory function; it is called defer(). The signature of this method is as follows:

Rx.Observable.defer(factoryFunction); 

It receives only one parameter, and this parameter is mandatory:

  • factoryFunction: This is a function that returns an observable

The following code shows an implementation of this method:

Rx.Observable     .defer(function(){         return Rx.Observable.just('Hello World');     })     .subscribe((data)=>console.log(data)); 

If you run this code, you will see the following output:

    Hello World
As the name implies, the defer() method only calls the factory function when ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required