1
votes

Based on the docs for RxJS's Observable.from(), it sounds like you should be able to pass it an object that implements the observable interface. However, the following

const observable = {
  subscribe(observer) {
    const subscription = someAsyncProcess(res => observer.next(res));

    return {
      unsubscribe() {
        subscription.unsubscribe();
      }
    }
  }
};


Rx.Observable.from(observable)
  .subscribe({
    next(res) {
      console.log(res);
    }
  });

throws the error

Uncaught TypeError: object is not observable

Is my observable implementation incorrect? Or am I misunderstanding from?

Note: this is more of an academic question about the Observable interface--I realize Observable.create() would work in the above situation.

2

2 Answers

1
votes

You can "trick" RxJS into thinking that the object you're passing it is a real Observable by implementing a "symbol function" (I don't know what is the proper name for this). However, you probably never need to do this in practise and it's better to use Observable.create.

const Rx = require('rxjs/Rx');
const Symbol_observable = Rx.Symbol.observable;
const Observable = Rx.Observable;

const observable = {
    [Symbol_observable]: function() {
        return this;
    },

    subscribe: function(observer) {
        // const subscription = someAsyncProcess(res => observer.next(res));
        observer.next(42);

        return {
            unsubscribe() {
                subscription.unsubscribe();
            }
        }
    }
};

Observable.from(observable)
    .subscribe({
        next(res) {
            console.log('Next:', res);
        }
    });

This prints:

Next: 42
0
votes

You can use Observable.from if it is an array of events or Observable.of if it is a simple object. It doesn't have to be implementing any interface. The code below is printing a in the console.

   Rx.Observable.from("a").subscribe(data=> console.log(data));