Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

353
Visualizações
Flatten array of observables return by switchMap() in pipe()

I have a method getFolders() which returns a Observable.

function getFolders() {

  const data = [
       {
          name: "Photos",
          files: of(2) // observable
       },
       {
          name: "Document",
          files: of(5) // observable
       },
       {
          name: "Videos",
          files: of(2) // observable
       }
  ];

  return of(data);

}

I need to get the total files count with is 9 (2+5+2). I wrote a function to do the job by the following usage,

getFileCount.subscribe( totalCount => console.log(totalCount) );

// expects to log 9

The implementation is,

function getFileCount() {

   return getFolders()
            .pipe(
               switchMap( folderData => folderData.map( data => data.files ) ),
               // Above switchMap returns [ Observable, Observable, Observable ]
               // Now I need to complete all Observable and get flatten result like [2,5,2]

               mergeAll(),
               // I though the mergeAll will resolve all Observables and return the value
               
               switchMap( countArray => {

                   // expecting all values in a single array [2,5,2]
                   // but it executes for each value like
                   // 2
                   // 5
                   // 2

                   console.log(countArray);

                   return countArray.reduce(function(a, b) { return a + b; }, 0);
               })
            );

}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use forkJoin to wrap the observable array and remove mergeAll(), it'll execute each observable inside

switchMap( folderData => forkJoin(folderData.map( data => data.files ) )),

         

          
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda