在RxJS 5中,有没有办法在订阅Observable之前触发它?

时间:2016-10-14 21:51:15

标签: rxjs5

我知道RxJS 5(以及其他地方)的可观察者是懒惰的。换句话说,在有订户之前,它们不会被执行。但是,我试图预取一些数据。有没有办法在订阅它之前触发observable?

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

1 个答案:

答案 0 :(得分:5)

你想做一个冷的可观察热。 (what are hot and cold observables

因此,如果您已经有冷观察,则可以使用publish运算符和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>
&#13;
&#13;
&#13;

但通常有一种更简单的方法。我假设您有一个外部事件源,您希望将其转换为可观察事件。正确的方法是使用Subject

&#13;
&#13;
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);
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.0-rc.1/Rx.js"></script>
&#13;
&#13;
&#13;