Mark
Mark

Reputation: 92440

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: http://reactivex.io/rxjs/manual/tutorial.html#creating-observables

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));
myObservable.next('foo');

Upvotes: 1

Views: 217

Answers (1)

cartant
cartant

Reputation: 58400

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

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 observer and if there isn't one, it does nothing:

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

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

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

  ...
}

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));
myObservable.next('foo');

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

Upvotes: 2

Related Questions