Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda