.unsubscribe 和 .take(1) 的区别 [英] Difference between .unsubscribe to .take(1)

查看:41
本文介绍了.unsubscribe 和 .take(1) 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,当 unsubscribe 之后使用 unsubscribe 时,使用 .take(1).unsubscribe 之间是否有任何性能差异订阅:

I wonder, if there is any difference in performance between using .take(1) and .unsubscribe when unsubscribe is used right after the subscription:

var observable = Rx.Observable.interval(100);

首先:

var subscription = observable.subscribe(function(value) {
   console.log(value);
}).unsubscribe();

第二:

var subscription = observable.take(1).subscribe(function(value) {
    console.log(value);
});

对它的任何想法对性能有什么不同吗?

Any ideas of it makes any different regard the performance?

推荐答案

每种方案都有不同的用途,因此很难进行比较.

Each serves a different purpose so it's hard to compare them.

一般来说,如果您采用此来源:

In general if you take this source:

const source = range(1,3);

... 并使用 subscribe() 后紧跟 unsubscribe() 使用它:

... and consume it with subscribe() followed immediately by unsubscribe():

source.subscribe(
  console.log,
  undefined, 
  () => console.log('complete')
).unsubscribe();

... 那么来自 source 的所有值都将被发出,即使我们在订阅后立即调用了 unsubscribe().这是因为代码仍然是严格顺序的(同步)并且 source 是一个冷 Observable.

... then all values from source are going to be emitted even though we called unsubscribe() right after subscribing. This is because the code is still strictly sequential (synchronous) and the source is a cold Observable.

1
2
3
complete

顺便说一句,尝试添加 delay(0) 操作符来制作 source.pipe(delay(0)).subscribe(...).unsubscribe().这使得使用实际的 setTimeout() 调用异步发出值,因此 unsubscribe() 在任何 next 处理程序之前被调用并被立即丢弃.

Btw, try adding delay(0) operator to make source.pipe(delay(0)).subscribe(...).unsubscribe(). This makes emitting values asynchronous using an actual setTimeout() call and for this reason unsubscribe() is called before any next handlers and is discarded immediately.

换句话说,unsubscribe() 让您随时停止接收值.即使源没有发出任何值(我们从未收到任何完整的通知).

In other words unsubscribe() let's you stop receiving values anytime. Even when the source hasn't emitted any value (we never receive any complete notification).

使用 take() 操作符限制链只发出特定数量的值.

Using take() operator limits the chain to only emit a specific number of values.

source.pipe(
  take(1),
)
.subscribe(
  console.log,
  undefined,
  () => console.log('complete')
);

这只是发出一个值并完成:

This just emits a single value and completes:

1
complete

即使你添加了 .unsubscribe() 结果也是一样的.

Even if you add .unsubscribe() the result would be the same.

观看现场演示:https://stackblitz.com/edit/rxjs-tbu5kb

所以 take() 是一个操作符,而 unsubscribe() 是一个 Subscription 对象.这两种东西通常可以互换,但它们永远不会完全相互替代.

So take() is an operator while unsubscribe() is a method on a Subscription object. These two things are often interchangeable but they never fully substitute each other.

2019 年 1 月:针对 RxJS 6 更新

Jan 2019: Updated for RxJS 6

这篇关于.unsubscribe 和 .take(1) 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆