RxJS 5 和缓存运算符的替代品

RxJS 5 and alternatives to the cache operator

在将 RxJS 升级到 5.0.0-rc.0 之前,我经常使用 .cache() 在我的 Angular 应用程序中共享订阅。使用它的最大优势是任何新订阅都将获得最后发布的值。

RxJS 团队决定删除它,现在我发现自己手动连接一个私有 BehaviorSubjectReplaySubject 然后一直调用 .asObservable()。考虑到我们之前必须采用的简单方法,这似乎有很多样板文件。

我错过了一些更简单的方法吗?我找不到 .replay() 运算符,.share().publishReplay() 运算符似乎也没有这样做。

谢谢!

这是我用来炫耀RxJS的。以下示例将最新模拟的 HTTP 响应缓存 1 秒。它基于通过 publishReplay()refCount().

的 RxJS 多播
var counter = 1;
var updateTrigger = Observable.defer(() => mockDataFetch())
    .publishReplay(1, 1000)
    .refCount()
    .take(1);

function mockDataFetch() {
    return Observable.of(counter++)
        .delay(100);
}

function mockHttpCache() {
    return updateTrigger;
}

mockHttpCache().toPromise()
    .then(val => console.log("Response from 0:", val));

setTimeout(() => mockHttpCache().toPromise()
    .then(val => console.log("Response from 200:", val))
, 200);

setTimeout(() => mockHttpCache().toPromise()
    .then(val => console.log("Response from 1200:", val))
, 1200);

setTimeout(() => mockHttpCache().toPromise()
    .then(val => console.log("Response from 1500:", val))
, 1500);

setTimeout(() => mockHttpCache().toPromise()
    .then(val => console.log("Response from 3500:", val))
, 3500);

观看现场演示:https://jsbin.com/todude/3/edit?js,console

这会打印到控制台:

Response 0: 1
Response 50: 1
Response 200: 1
Response 1200: 2
Response 1500: 2
Response 3500: 3