javascript - 如何使用 Observables 代替 Promise?

标签 javascript angular promise es6-promise reactivex

我有一个带有一些方法的服务,其中大多数需要完成特定的回调才能完成其工作。使用伪 promise ,可以很容易地做到这一点:

ready = http.get(stuff); // Returns a promise, resolves after a while

methodOne() { // methods sometimes called before promise resolves
    this.ready.then(_ => { 
        // doStuff
    });
}

methodTwo() {
    return this.ready.then(d => {
        // doOtherStuff
    });
}

基本上,只有当我确定服务已准备好时,我才需要做这些事情。 我实际上只需要检查它是否准备好了(methodOne 正在做什么,只需用 methodTwo 来说明,也很容易做更多事情)。

我想尝试全力以赴开发 Observables,但对于这个具体案例,我发现很难与类似的 Observables 解决方案竞争。

Promise 会记住该值并知道它是否得到解决。 Observable 稍微复杂一些,并且创建相同的流程似乎很麻烦。我需要订阅 Observable 的任何内容,以便知道它何时准备好。有时该方法会被提前调用 - 在 Observable 发出之前,有时会在 Observable 发出之后被延迟调用。

我现在有这个,但它似乎不起作用:

this.ready$ = someObservable // Will fire after a litle while but never finish - i only need the first to check though.
  .publishReplay(1).refCount(); // Trying to replay if subscription comes after emit.

this.ready$.subscribe(_ => {
    // This will be called
});

methodOne() { 
    this.ready$.subscribe(_ => {
        // Not called
    });
};

也许我误解了 publishReplayrefCount 的使用?

最佳答案

我认为您正在寻找的是 AsyncSubject 。它很好地模仿了 promise 的行为。说明如下:

The AsyncSubject is a variant where only the last value of the Observable execution is sent to its observers, and only when the execution completes.

以下是如何在您的案例中使用它:

subject = new AsyncSubject();
ready = streamOfData(stuff).first().subscribe(subject);    
methodOne() {
    return this.subject.asObservable();
}

主题订阅由 first 运算符返回的底层可观察对象,并等待它完成。它收集所有订阅者,但不向他们发送任何值。一旦底层可观察对象完成,它就会记住该值并将其发送给收集的订阅者。所有新的 future 订阅者将立即传递此存储的解析值。

这是一个简单的示例,演示您可以在可观察对象完成之前或之后进行订阅:

const subject = new AsyncSubject();
const o = subject.asObservable();
o.subscribe((v) => {
  console.log(v);
});
interval(500).first().subscribe(subject);

setTimeout(() => {
  o.subscribe((v) => {
    console.log(v);
  });
}, 2000);

关于javascript - 如何使用 Observables 代替 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45466563/

相关文章:

javascript - 如何在 javascript 类完成后获得最终响应

javascript - 如何在 Promise all 错误中获取结果数组

javascript - 使用 jQuery 将 Feb 17, 2012 转换为 17/02/2012

javascript - 如何在 HTML 输入字段的末尾自动添加 .com?

javascript - TypeError:未定义不是函数 - Sails.js

javascript - 如何在模式打开时停止触发 TAB 键事件

javascript - 使用 Promise 异步设置变量并避免回调

javascript - 当最后一只猫显示完整图像时如何发出警报?

angular - 构建具有多个配置的应用程序

html - 当 ViewContainerRef 被注入(inject)指令时,它绑定(bind)到什么元素?