Array map和rxjs map有什么区别 [英] What are the differences between Array map and rxjs map

查看:150
本文介绍了Array map和rxjs map有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道rxjs和array上的映射以相同的方式工作.数组映射方法和rxjs映射运算符的用法之间有什么区别?

I was wondering what the map on both rxjs and array works the same way. What are the differences between the uses of both the array map method and rxjs map operator?

推荐答案

Array.map转换单个数组的每个元素.

console.log( [ 1, 2, 3 ].map(x => x * x) )
// log: [ 1, 4, 9 ]


通常,RXJS Observables更像是数据流,但是每个数据都是其自己的实体.


In general, RXJS Observables are more like a stream of data, but each data is its own entity.

您可以选择将数组存储在Observable中,但仍将每个数组视为单个实体.每次调用Subject#next时,都会提供一个全新的数组.在这种情况下,RXJS不等同于Array#push,因为RXJS不会关心观察对象的内容恰好是数组.

You may choose to store arrays in your Observable, but still, each array is treated like a single entity. Every time you call Subject#next, you're providing an entirely new array. In this scenario, there is no equivalent to Array#push with RXJS, because RXJS doesn't care that the content of the Observable happens to be an array.

// Observable that holds an array as its type
const subject: Subject<number[]> = new Subject<number[]>();
subject.pipe(
  // the value here is a full array
  map(arr => arr.map(x => x * x))
).subscribe(arr => console.log(arr));

subject.next([ 1, 2, 3 ]);
// log: [ 1, 4, 9 ]

subject.next([ 7, 8, 9 ]);
// log: [ 49, 64, 81 ]


*奖励:如果设置ReplaySubject,则可以 kinda 使某些行为更像数组. Subject的此实现从字面上重播提供给它的所有数据(或基于实例化它的子集).就像您将看到的那样,它的局限性在于您只能推到最后,您必须创建一个新的订阅才能看到整个数组",但这仍然是一个有趣的思想实验.


* Bonus : You can kinda make something act more like an array if you set up a ReplaySubject. This implementation of Subject literally replays all the data that was given to it (or a subset based on how you instantiate it). As you'll see though, the limitation to this would be that you can only push onto the end, and you have to create a new subscription to see the entire "array", but it's an interesting thought experiment nonetheless.

const subject: ReplaySubject<number> = new ReplaySubject<number>();
subject.next(1);
subject.next(2);
subject.next(3);

const transformed: Observable<number> = subject.pipe(
  map(x => x * x)
);

transformed.pipe(first()).subscribe(x => console.log(x));
// log: 1
// log: 4
// log: 9

subject.next(9);
transformed.pipe(first()).subscribe(x => console.log(x));
// log: 1
// log: 4
// log: 9
// log: 81

这篇关于Array map和rxjs map有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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