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

252
Visualizações
update Observable method with if/else to use reactive style

I have the below method which I'd like to update to a more reactive style. it contains if/else logic. I've read that you should be able to decompose into streams, apply a filter to each stream and merge back the streams but I'm unsure as to how to apply this to the below example.

The sample method below passes an exclude flag. the method first calls out to a http service to get an array. if the exclude flag if true we then need to call out to another http service to get some config data which is needed to filter the array.

Thanks for your help.

method A(boolean excludeSomeCatagory ) : Observable<Species[]> {
  return Observable.create((observer) => {
    getSomeHttpData().subscribe((species: Species[]) => {
      if(!excludeSomeCatagory){
        observer.next(species);
        observer.complete();                                  
      }
      else {
        getSomeConfigDataFromHttp().subscribe(
          (data) => {
          filteredArray: Species[] = applyFilter(data, species);
          observer.next(filteredArray);
          observer.complete();                                                    
        });                                          
      }                             
    });
  }
}             
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Something like this would work:

public A(excludeSomeCategory: boolean): Observable<Species[]> {
    return getSomeHttpData().pipe(
        switchMap(species => {
            return !excludeSomeCategory
                ? of(species)
                : getSomeConfigDataFromHttp().pipe(
                    map(data => applyFilter(data, species))
                )
        })
    );
}     

The overall idea is that you start your stream with an observable from your http call, then pipe it's emission into the shape you need. You will rarely have the need to create an observable using Observable.create() because rxjs offers plenty of static operators handling many common use cases.

You also want to avoid subscriptions that you can't easily clean up (nested subscriptions).

So, if we were to simply return getSomeHttpData(); this would be of type Observable<Species[]>.

public A(): Observable<Species[]> {
   return getSomeHttpData();
}

Obviously, you have some more logic you want to do to potentially make an additional api call, so we pipe the emission (Species[]) to switchMap which will subscribe to an "inner observable" for you and emit its emissions.

So, inside of switchMap you want to return an observable. In your case, you have a condition that may simply return the receive emission OR will make another http call.

For the case when you want to emit the prior emission, we use of to create an observable out of the plain value.

In the other case, we simply return the call to getSomeConfigDataFromHttp() which itself returns an observable. Since you want to transform the data a bit, we use map to handle that.

over 4 years ago · Santiago Trujillo Relatório

0

Just return the Observable directly and use a SwitchMap.

method A(boolean excludeSomeCatagory ) : Observable<Species[]> {
    return getSomeHttpData().pipe(
        switchMap((species) => {
            if(!excludeSomeCatagory){
                return of(species)
            } else {
                return getSomeConfigDataFromHttp().pipe(
                    map(data => {
                        return applyFilter(data, species)
                    })
                )
            }
        })
    )
}
over 4 years ago · Santiago Trujillo 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