0

Using rxjs 5, I want to subscribe to an observable and begin the stream with the last emitted value. The operator '.cache' is supposed to be built for this (I think) but I can't get it to work. I did a small test where fire an observable (by clicking a button) then subscribe to it 3 seconds later. In theory, I should get that click emission upon subscription, but I don't.

https://github.com/ReactiveX/RxJS/commit/4308a04

http://codepen.io/BradLee/pen/VaqreL

let btn = document.querySelector(`btn`),
    btn$ = Rx.Observable.fromEvent(btn, `click`)
             .cache(1);

setTimeout(() => { 
    btn$.subscribe(evt => console.log('fired') );
}, 3000);
Brad Woods
  • 1,507
  • 2
  • 12
  • 30

1 Answers1

1

The problem is not related to RxJS. Your query selector is incorrect, if you change:

let btn = document.querySelector(`btn`),

to

let btn = document.querySelector('button')

It works.

edit

Until there is at least one subscription with cache it won't emit any events. If you need to receive events from before the subscribe occurs you either need to create an immediate subscription so that you can start receiving events.

let btn = document.querySelector(`btn`),
    btn$ = Rx.Observable.fromEvent(btn, `click`)
             .cache(1);

btn$.subscribe();

Or you need to use the publishReplay operator and connect with it instead:

let btn = document.querySelector(`btn`),
    btn$ = Rx.Observable.fromEvent(btn, `click`)
             .publishReplay(1);

btn$.connect();
paulpdaniels
  • 18,395
  • 2
  • 51
  • 55
  • that was a problem but it doesn't solve the rxjs problem. If you click the button before the 3 second timer fires you should get a console msg when the timer fires, but you don't. – Brad Woods May 14 '16 at 02:56
  • That is expected behavior. You haven't subscribed to the `Observable` yet so it can't receive any events yet. I edited with a solution for that as well. – paulpdaniels May 14 '16 at 05:52