【问题标题】:Angular Rxjs: Have concat wait for a very long tapAngular Rxjs:让 concat 等待很长时间
【发布时间】:2021-02-11 13:29:05
【问题描述】:

我正在尝试自动化更新程序后端中某些数据的过程。 我正在使用我的 Angular 前端,在那里我创建了一个只有主用户才能访问的功能,这应该让他登录每个管理(租户),在那里它将下载一些内部包含错误数据的对象,从谷歌服务询问正确的数据并在后端更新数据,并为每个租户执行所有这些操作。

我想把每一个操作写成一个 observable 并使用 concat 来按顺序做所有事情,但是在我完成获取正确数据之前,我在一个水龙头里做的,它已经尝试登录下一个租户,所以当它实际上有正确的数据时,他将无法将它们上传到后端,因为它会拒绝它们来自错误的租户。

我认为这个问题是由水龙头中需要的长时间操作引起的(我需要做一些事情需要更多时间),。

这是我的代码 sn-p(没有无关的东西):

const obsList = [] as Observable<any>[];
this.assignedTenants.forEach(tenant => {
  const obsList2 = [] as Observable<any>[];
  obsList.push(this.authenticationService.login(new Credentials(usr, psw), tenant.id));
  obsList.push(this.structureService.getStructuresWithWrongAltitude()
    .pipe(tap(structuresReceived => {
      obsList2 = [] as Observable<any>[];
      if (structuresReceived != null && structuresReceived.length > 0) {
        structuresReceived.forEach(s => {
          this.getElevation(new google.maps.LatLng(s.centro.coordinates[0], s.centro.coordinates[1]))
            .then(a => {
              s.centroAltitudine = a;
              this.obsList2.push(this.structureService.putStructure(s));
            })
            .catch();
        });
      }
  })));
  obsList.push(forkJoin(obsList2)
    .pipe(tap(() => this.storageService.logout())));
});
concat(...obsList).subscribe();

如你所见,这段代码应该为每个租户创建并执行 3 个 observable,第一个用于登录,第二个用于获取错误数据,获取正确数据并为第三个做准备,这将更新数据。 正如我所说,通常当从第二个可观察对象 getStructuresWithWrongAltitude 进入水龙头时,我已经可以通过使用日志看到它尝试登录到其他租户。

我的理论是,一旦它得到错误的数据,它就会尝试执行仍然无效的第三个 observable,然后转到下一个租户,但我不知道如何解决这个问题。

我需要一种方法让第二个 observable 在点击完成之前不发射,或者另一种方法来防止 concat 在其他操作完成之前继续

感谢您的帮助

编辑:

我能够通过将 getElevation(它返回一个承诺)设置为一个可观察列表来解决这个问题,该列表又会创建一个新的可观察列表来保存数据。

正如我之前所说,我需要做一些非常相似的事情,不同的是这次水龙头实际上需要做很多需要很长时间的计算,所以我不能使用相同的修复,因此我的问题仍然存在:我可以让 concat 等到点击完成吗?

为澄清而编辑 2

正如我在上次编辑中所说,通过将 tap 中的内容转换为其他 observables 解决了该特定示例,但我在另一个函数中遇到了几乎相同的问题

此功能需要在文件夹中查找文件,然后才能上传文件

const folderInput = this.folderInput.nativeElement;
folderInput.onchange = () => {
  this.filesUploaded = folderInput.files;
  const obsList = [] as any[];

  this.assignedTenants.forEach(tenant => {
    const obsList2 = [] as Observable<any>[];

    obsList.push(this.authenticationService.login(new Credentials(usr, psw), tenant.id));

    obsList.push(this.fileService.getAll()
      .pipe(
        tap(filesReceived => {
          if (filesReceived != null && filesReceived.length > 0) {
            console.log('upload picture: received list of files to update');

            let i = filesReceived?.length;
            filesReceived?.forEach(f => {
              const pathReceived = (f.originalFilename as string).substr(1).split('\\');

              let found = false;
              let index = -1;
              
              // searching the file in the folder
              //...
              
              if (found) {
                console.log('found a file');
                const selectedFile = this.filesUploaded[index];
                const formData = new FormData();
                formData.append('file', selectedFile, selectedFile.name);
                obsList2.push(this.fileService.updateFile(formData, f.id));
              }
              i--;
            });
            console.log('upload picture: updated obsList2');
            obsList.push(forkJoin(obsList2).subscribe(() => {
              console.log('upload picture: uploaded pictures');
              this.storageService.logout();
            }));
          }
      }))
    );
  });

  this.loadingIndicatorService.loading$.next(true);
  let counter = obsList.length;
  concat(...obsList).subscribe(() => {
    counter--;
    console.log('upload pictures: remaining phases: ' + counter);
    if (counter <= 0) {
      this.loadingIndicatorService.loading$.next(false);
  }
});
};
folderInput.click();

【问题讨论】:

  • 这里有几处不明白的地方,但第一个与常量obsList2有关。您在第三行声明它,然后在第七行使用代码obsList2 = [] as Observable&lt;any&gt;[]; 重置它。你确定这在 Typescript 中真的有效吗?一旦我们澄清了这一点,我们就可以继续进行其余的工作。
  • 你试过这个 SO 帖子吗? stackoverflow.com/questions/43336549/…。本文还讨论了事件排序 - juristr.com/blog/2019/01/Guarantee-Event-Order-with-RxJS
  • @Picci 是的,它有效,我只是再次将其设为空以确保,但它不会产生任何错误或警告
  • @AndyDangerGagne 问题不是按顺序执行它们,而是让它们等待第二个管道的水龙头,这需要一些时间。正如我所说,示例中的问题已解决,但它不适用于更复杂的水龙头。

标签: rxjs concatenation rxjs-observables rxjs-pipeable-operators rxjs-pipe


【解决方案1】:

简而言之:否

您可以永远永远让同步代码等待 JavaScript 中的异步代码。 JS 在一个线程上运行,如果您尝试这样做,您的程序将停止。 JS 确实有 async-await 让它看起来像同步代码正在等待(但它只是将延续放在事件循环上,根本不等待)。

另一方面,tap 中的所有同步代码将在可观察管道的下一部分执行之前完成(100% 的时间)。

但是

有个好消息,你永远不需要

您永远不需要同步代码来等待 JavaScript 中的异步代码。如果您使用的是 observables,那么您拥有决定代码运行顺序所需的所有工具。

如果在您的tap 中,如果您有.then 或.subscribe,那么您可能做错了什么。在 RxJS 中,这被认为是代码异味是有充分理由的。

您的代码(就目前而言)很难阅读,因此很难获得比您尝试的内容更广泛的内容。

我是这样理解的:

对于每个用户:

  1. 使用 id 登录用户
  2. call this.fileService.getAll() // 这是作为登录用户完成的吗?您的服务会为您处理这个问题吗?
  3. 对 0+ 个文件调用 this.fileService.updateFile

这是一个粗略的尝试。这绝对不会编译。另外,如果我对你的 observables 的功能有更多的了解,它可以被清理掉,但是从上面显示的代码来看,它们有点神秘。

from(this.assignedTenants).pipe(
  concatMap(tenant => concat(
    this.authenticationService.login(new Credentials(usr, psw), tenant.id),
    this.fileService.getAll().pipe(
      switchMap(filesReceived => forkJoin(
        filesReceived.map(f => {
          //Code to get formData and such
          if(found){
            return this.fileService.updateFile(formData, f.id);
          }
          return null;
        }).filter(v => v != null)
      )
    ))
  )),
).subscribe(result => {
  console.log("Result of forkjoin: ", result);
}

一些重构:

/*****
 * An Observable that gets all files, updates them, then completes
 *****/
function updateFiles(): Observable<any[]>{
  return this.fileService.getAll().pipe(
    // This map should turn every file received into either:
    //  1. A service call to update that file
    //  2. null
    map(filesReceived => filesReceived.map(f => {
      //Code to get formData and such
      if(found){
        return this.fileService.updateFile(formData, f.id);
      }
      return null;
    })),
    // Filter out null entries in our serviceCalls array
    map(serviceCalls => serviceCalls.filter(
      serviceCall => serviceCall != null
    )),
    // subscribe to all our service calls at once
    switchMap(serviceCalls => forkJoin(serviceCalls))
  );
}

from(this.assignedTenants).pipe(
  // ConcatMap won't start the second tenant until the first one's 
  // updateFiles() observable completes.
  concatMap(tenant => concat(
    this.authenticationService.login(new Credentials(usr, psw), tenant.id),
    updateFiles()
  )),
).subscribe({
  next: result => console.log("The Result of login(...) or updateFiles()", result),
  complete: () => console.log("Every file for every tenant is done")
})

【讨论】:

  • @MassimoDeFacci4EmmeService 我花了一点时间重构和评论我发给你的代码。它仍然不会按原样编译,但我尝试创建一些关注点分离,以将映射、过滤、forkJoining 分解为单独的功能,以便更容易阅读。希望这是一个更好的开始/学习的地方。
【解决方案2】:

如果我理解了问题的核心,我认为核心点是tap中的操作是异步的,所以tap不是完全正确的操作符,如果你想等待的结果它。所以你最好使用concatMap之类的东西。 我要做的另一件事是将 Promise 转换为 Observable,然后使用管道对其执行 fetch 操作,调用 Google 服务,然后进行更新。 最后一点是关于最后使用concat。这意味着您将依次攻击每个租户。如果这是您想要执行的操作,则可以。如果您认为可以并行进行,您可能需要考虑将concat 替换为forkJoin。

代码看起来像这样。

const obsList = [] as Observable<any>[];
this.assignedTenants.forEach(tenant => {
  obsList.push(
    // create here an Observable which executes login, fetch the wrong data, ask Google for the right data and update sequentially
    this.authenticationService.login(new Credentials(usr, psw), tenant.id)).pipe(
      concatMap(() => this.structureService.getStructuresWithWrongAltitude()),
      concatMap(structuresReceived => {
        const obsList3 = [] as Observable<any>[];
        if (structuresReceived != null && structuresReceived.length > 0) {
          structuresReceived.forEach(s => {
            // transform the Promise into an Observable using the from function
            // and then concatenate with the update operation
            obsList3.push(
              from(this.getElevation(new google.maps.LatLng(s.centro.coordinates[0], s.centro.coordinates[1]))).pipe(
                concatMap(a => {
                  s.centroAltitudine = a;
                  return this.structureService.putStructure(s)
                ),
              )
            )
          }
        }
        // execute the calls to Google in parallel and  (for each tenant)
        return forkJoin(obsList3)
      }),
      concatMap(() => this.storageService.logout())
    )
  });
});
concat(...obsList).subscribe();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多