Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the code inside RxJS Observable constructor not being called?

If I do this in browser console, the constructor function doesnot seems to be called-

Observable.create(observer =>
   console.log('this is the observer'); //doesn't gets logged
   this.alertObserver = observer
);

or this :-

new Observable(observer =>
   console.log('this is the observer'); //doesn't gets logged
   this.alertObserver = observer
);

I have tried importing Observer through

import {Observable} from 'rxjs/Observable'; 

and

import {Observable} from 'rxjs/Rx';

but with no help.

Any suggestion ?

like image 294
VISHAL DAGA Avatar asked Jul 17 '26 01:07

VISHAL DAGA


2 Answers

Rx observables are lazy loaded. You need at least one subscriber.

Try:

var observable = Observable.create(observer =>
   console.log('this is the observer'); 
   this.alertObserver = observer
);
observable.subscribe();
like image 53
pixelbits Avatar answered Jul 21 '26 05:07

pixelbits


Not this:

import {Observable} from 'rxjs/Rx';

This: import {Observable} from 'rxjs';

like image 45
Chuck Avatar answered Jul 21 '26 03:07

Chuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!