【问题标题】:Comparing an old and new subscription values in an array after an update更新后比较数组中的新旧订阅值
【发布时间】:2020-08-20 22:53:18
【问题描述】:

我有以下 observable 在 workspace 上获得 pages

page$ = this.pageService.getPages(this.workspaceId) // .subscribe() to get data

添加新页面时会定期更新。

我想在添加新页面(或页面流)之前和之后保存页面数组,然后能够比较它们。

例如,在 init 上,如果有三页,arrayOld 将是这三页。然后,如果添加一个新页面,则会创建一个新的数组,arrayNew,有四个页面。

如果页面随后被删除,arrayOld 将变为 arrayNew(长度为 4),arrayNew 将变为新的页面集(长度为 3)。

我还没有找到一种简单的方法来完成此操作,将subscribe() 用于当前页面流。

这里的任何帮助都会很棒。谢谢!

【问题讨论】:

标签: angular rxjs observable


【解决方案1】:

也许是这样的:

import { Observable, of } from 'rxjs';

const observable = of([1],[1,2], [1],[1,3],[1,3,4],[1,3,4,5]);

let arrayOld = [];
let arrayNew = [];

observable.subscribe(a => {
  arrayOld = JSON.parse(JSON.stringify(arrayNew));
  arrayNew = JSON.parse(JSON.stringify(a));
  
  console.log("---------------");
  console.log("old:", arrayOld);
  console.log("new:", arrayNew);
});

当页面(删除和添加)用数字编码时:

[1]: initially there is only page id=1
[1,2] added page id=2
[1] deleted page id=2
[1,3] added page id=3,
[1,3,4] added page id=4
[1,3,4,5] added page id=5

JSON.parse(JSON.stringify(arrayNew)): 用于深拷贝数组

这是一个堆栈闪电战: https://tzb2jv.stackblitz.io

【讨论】:

    【解决方案2】:

    使用pairWise 运算符。这是一个例子:

    const pages$: Observable<string[]> = of(
      ['Page1', 'Page2', 'Page3'],
      ['Page1', 'Page2', 'Page3', 'Page4'],
      ['Page1', 'Page2', 'Page3', 'Page4', 'Page5'],
    );
    
    pages$.pipe(
      startWith([]),
      pairwise(),
    ).subscribe(
      ([arr1, arr2]) => console.log(arr1, 'changed to', arr2),
    );
    

    输出:

    []
    changed to
    ["Page1", "Page2", "Page3"]
    
    ["Page1", "Page2", "Page3"]
    changed to
    ["Page1", "Page2", "Page3", "Page4"]
    
    ["Page1", "Page2", "Page3", "Page4"]
    changed to
    ["Page1", "Page2", "Page3", "Page4", "Page5"]
    
    

    【讨论】:

      【解决方案3】:

      scan 就像一个 reduce 函数,你可以有一个累加器来返回前一个和当前。

      const { of } = rxjs;
      const { scan } = rxjs.operators;
      
      of([1,2], [1,2], [3, 4], [3, 4]).pipe(
        scan((acc, current) => {
          acc.previous = acc.current;
          acc.current = current;
          return acc;
        }, {})
      ).subscribe(({ current, previous }) => {
        const added = previous ? current.filter(i => !previous.includes(i)) : current;
        const deleted = previous ? previous.filter(i => !current.includes(i)) : [];
        console.log('Added: ', added);
        console.log('Deleted: ', deleted);
      });
      &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js"&gt;&lt;/script&gt;

      【讨论】:

      • 我刚刚阅读了 Alif50 链接到的答案,这是一个不错的解决方案。我不知道成对
      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多