What are the differences between Array map and rxjs map

前端 未结 3 2165
误落风尘
误落风尘 2021-02-20 14:07

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?

3条回答
  •  没有蜡笔的小新
    2021-02-20 14:25

    Array.map transforms each element of a single array.

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

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

    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 = new Subject();
    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 ]
    

    * 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 = new ReplaySubject();
    subject.next(1);
    subject.next(2);
    subject.next(3);
    
    const transformed: Observable = 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
    

提交回复
热议问题