Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!