I know observables in RxJS 5 (and elsewhere) are lazily executed. In other words, they aren't executed until there is a subscriber. However, I'm trying to prefetch some data. Is there a way to trigger the observable before subscribing to it?
let obs = Rx.Observable.create(observer => {
console.log('Observer executed');
// This would actually be fetching data from a server:
observer.next(42);
});
// Something like obs.warmup() happens here
console.log('Observer is ideally called before this point.');
// Some time later this is called, and hopefully the data is already retrieved.
obs.subscribe(value => {
console.log('Got ' + value);
});
You would like to make a cold observable hot. (what are hot and cold observables)
So if you already have a cold observable you can use the publish operator alongside with connect.
let obs = Rx.Observable.create(observer => {
console.log('Observer executed');
// This would actually be fetching data from a server:
observer.next(42);
}).publish(); // create a ConnectableObservable
obs.connect(); // Run the observer
// Something like obs.warmup() happens here
console.log('Observer is ideally called before this point.');
// Some time later this is called, and hopefully the data is already retrieved.
obs.subscribe(value => {
console.log('Got ' + value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.0-rc.1/Rx.js"></script>
But usually there is a much simpler way. I assume you have an external source of events, which you want to convert to an observable. The correct way is to use a Subject.
let obs = new Rx.Subject();
console.log('Observer executed');
obs.next(42); // subscribers would receive this...
// it could be something like `service.on("event", e => obs.next(e));`
// Something like obs.warmup() happens here
console.log('Observer is ideally called before this point.');
// Some time later this is called, and hopefully the data is already retrieved.
obs.subscribe(value => {
console.log('Got ' + value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.0-rc.1/Rx.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With