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

In RxJS 5, is there a way to trigger an Observable before subscribing to it?

我知道 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);
});

您想使冷的 Observable 变热。 (what are hot and cold observables)

因此,如果您已经有了冷可观察对象,则可以使用 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>

但通常有更简单的方法。我假设您有一个外部事件源,您希望将其转换为一个可观察对象。正确的方法是使用 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>