【问题标题】:Idiomatic way to handle a stream end with RxJS使用 RxJS 处理流结束的惯用方式
【发布时间】:2015-07-29 16:28:39
【问题描述】:

我需要在流结束时执行一些操作。这样做的惯用方法是什么?

现在我使用下面的代码:

source.subscribe(undefined, undefined, function() {
  socket.send({type: 'end'});
});

【问题讨论】:

    标签: system.reactive reactive-programming rxjs


    【解决方案1】:

    有几种方法可以做到这一点:

    1. 使用运算符subscribeOnCompleted() 而不是将空值传递给.subscribe 方法。

    2. 使用tapOnCompleted(),与上面相同,但它不会启动序列,您可以在序列的中途注入它。

    3. 使用.finally(),它将在序列完成时执行(正常或其他方式)。

    4. 在您的示例中,您展示了一个副作用,但如果您正在清理资源,则使用 .using() 会更符合语义,它需要一次性并将其与订阅的生命周期联系起来。

    这些看起来像:

    1. source.subscribeOnCompleted(() => socket.send({type: 'end'}));

    2. source.tapOnCompleted(() => socket.send({type: 'end'})).subscribe()

    3. source.finally(() => socket.send({type: 'end'})).subscribe()

    4. Rx.Observable.using(() => createResource(), (resource) => source).subscribe()

    【讨论】:

    • 我想在我的情况下tapOnCompleted 是最好的方法
    猜你喜欢
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多