MarkM MarkM - 1 year ago 91
Javascript Question

Why doesn't this simple rxjs example behave as expected

I am trying to get a more solid understanding of the basics of reactive programming, so I'm going through the examples here:

I'm just typing them in a text editor and running them in the terminal via node. The very first example produces no output (the second one works, so it's not an issue loading the library). I'm expecting it to output 'foo', but I get nothing. Why?

var myObservable = Rx.Subject.create();
myObservable.subscribe(value => console.log(value));'foo');

Answer Source

Calling Rx.Subject.create() without arguments creates an AnonymousSubject that does not have a destination observable:

export class Subject<T> extends Observable<T> implements ISubscription {


  static create: Function = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {
    return new AnonymousSubject<T>(destination, source);


The AnonymousSubject implementation of next simply forwards the call to the destination observable and if there isn't one, it does nothing:

export class AnonymousSubject<T> extends Subject<T> {

  constructor(protected destination?: Observer<T>, source?: Observable<T>) {
    this.source = source;

  next(value: T) {
    const { destination } = this;
    if (destination && {;


So the example in your question does nothing. It's possible that this is a simple error in the tutorial, as the following will see foo logged to the console:

var myObservable = new Rx.Subject();
myObservable.subscribe(value => console.log(value));'foo');

Note that the above code creates a Subject, rather than an AnonymousSubject.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download