angularrxjsobservablerxjs-pipeable-operatorsrxjs-marbles

swap element in an observable array


I am trying to swap two items in the observable array. I know how to do it in the normal array. I tried the same way but it doesn't change the value.

My Stackblitz code

Here is what I tried,

swapObservableArray() {
    let index;

    // get the index
    this.productss$
      .pipe(findIndex((a) => a.id === 5))
      .subscribe((a) => (index = a));

    // swap the items
    [this.productss$[2], this.productss$[index]] = [
      this.productss$[index],
      this.productss$[2],
    ];
    this.productss$.subscribe((a) => console.log(a));
  }

Solution

  • Is that what you tried to achieve? Please pay attention that I also modified how productss$ is initialized.

    Stackblitz code

    
    import { Component } from '@angular/core';
    import { Observable, of } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    interface fruits {
      name: string;
      id: number;
    }
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      productss$: Observable<fruits[]> = of([
        { name: 'orange', id: 1 },
        { name: 'grapes', id: 2 },
        { name: 'mango', id: 3 },
        { name: 'kiwi', id: 4 },
        { name: 'strawberry', id: 5 },
        { name: 'blueberry', id: 6 },
      ]);
      normalProduct: fruits[] = [
        { name: 'orange', id: 1 },
        { name: 'grapes', id: 2 },
        { name: 'mango', id: 3 },
        { name: 'kiwi', id: 4 },
        { name: 'strawberry', id: 5 },
        { name: 'blueberry', id: 6 },
      ];
    
      constructor() {}
      ngOnInit() {
        this.swapNormalArray(); // works
        this.swapObservableArray(); // doesn't work
      }
    
      swapNormalArray() {
        // find the index
        const index = this.normalProduct.findIndex((a) => a.id === 5);
        // swap the item
        [this.normalProduct[2], this.normalProduct[index]] = [
          this.normalProduct[index],
          this.normalProduct[2],
        ];
        console.log('Normal', this.normalProduct);
      }
      swapObservableArray() {
        this.productss$
          .pipe(
            map((value: fruits[]) => {
              const idx = value.findIndex((a) => a.id === 5);
              [value[2], value[idx]] = [value[idx], value[2]];
              return value;
            })
          )
          .subscribe((a) => console.log('Observable Array', a));
      }
    
      ngOnDestroy() {}
    }