0
votes

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);
1

1 Answers

1
votes

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();