簡體   English   中英

Angular Rxjs:連續等待很長時間

[英]Angular Rxjs: Have concat wait for a very long tap

我正在嘗試自動化更新程序后端中某些數據的過程。 我正在使用我的 Angular 前端,在那里我創建了一個只有主用戶可以訪問的 function,這應該讓他登錄每個管理(租戶),它會下載一些內部包含錯誤數據的對象,從谷歌服務詢問正確的數據並在后端更新數據,並為每個租戶執行所有這些操作。

我想把這些操作中的每一個寫成一個可觀察的並使用 concat 來按順序做所有的事情,但是在我完成獲得正確的數據之前,我在水龍頭里做的,它已經嘗試登錄下一個租戶,所以當它實際上擁有正確的數據,他將無法將它們上傳到后端,因為它將拒絕來自錯誤的租戶。

我認為這個問題是由水龍頭中所需的長時間操作引起的(我需要做一些事情,這將需要更多時間),。

這是我的代碼片段(沒有無關的東西):

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,它仍然是無效的,並且 go 到下一個租戶,但我不知道如何解決這個問題。

我需要一種方法讓第二個 observable 在點擊完成之前不發射,或者在其他操作完成之前防止連接到 go

謝謝您的幫助

編輯:

我可以通過將 getElevation (返回一個承諾)設置為一個可觀察列表來解決這個問題,該列表又會創建一個新的可觀察列表來保存數據。

正如我之前所說,我需要做一些非常相似的事情,不同的是這次水龍頭實際上必須做很多需要很長時間的計算,所以我將無法使用相同的修復,因此我的問題仍然存在:我可以讓 concat 等到點擊完成嗎?

編輯2澄清

正如我在上次編輯中所說,通過將水龍頭內的東西轉換為其他可觀察對象來解決該特定示例,但另一個 function 的問題幾乎相同

這個 function 需要在文件夾中找到文件,然后再上傳

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();

如果我理解了問題的核心,我認為核心點是tap中的操作是異步的,所以如果你想等待它的結果, tap並不是完全正確的操作符。 所以你最好使用concatMap類的東西。 我要做的另一件事是將 Promise 轉換為 Observable,然后對它使用 pipe 來執行提取操作,調用 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();

簡而言之:沒有

永遠不能讓同步代碼等待 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

這是一個粗略的 go 。 這絕對不會編譯。 此外,如果我對你的 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")
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM