rxjs: Observables cannot be passed between window contexts.

RxJS version: 5.4

Code to reproduce:

if (window.opener) {
  window.myObservable = window.opener.myObservable;
} else {
  window.myObservable = Rx.Observable.of(1, 2, 3);
  window.open(location.href);
}

window.myObservable
  .switchMap(function(x) {
    return Rx.Observable.of(x);
  })
  .subscribe(function(x) {
    console.log(x);
  });

Expected behavior: Both parent and child window should print 1, 2, 3 to the console.

Actual behavior: The child window throws an exception because myObservable from the parent window’s context cannot be identified as an Observable in the child window’s context.

Additional information: The issue is caused by a reliance on instanceof for determining if an object is an Observable which fails for objects passed between javascript contexts. Instead, a more robust solution would test for the shape of an Observable, perhaps using a type guard similar to isPromise

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 20 (13 by maintainers)

Commits related to this issue

Most upvoted comments

If it can be of any help, I couldn’t make it work with

Observable.from(originalObservable);

But I got it working with

Observable.create(observer => originalObservable.subscribe(observer))

Ah good to see that I was not just going crazy 😜 .

I think this is related to #2489 too, since things would get more complicated if we do this:

import switchMap from 'rxjs/somewhere/switchMap'

window.myObservable  // <---- from context B, previously assigned
  .pipe(switchMap(function(x) {  // <---- pipe from context B, switchMap from context A
    let X = Rx.Observable.of(x); // <----- run in window A, using Rx from context A
    return X;
  }))
  .subscribe(function(x) {
    console.log(x);
  });

at that point switchMap is from context B and for everything done during the setup phase of the Observable it can only assume valid what is from context B, while it is asked to work on something from context A, through pipe.

I agree that we should rely less on instanceof and use duck-typing instead. I know it’s not robust, but JavaScript itself isn’t robust.