9

I want to use observable to be able to run my code synchronously, I want to return a true value after i get the icons from the server so that i can use it. How do i do it ?

ngOnInit() {
  this.addIcons().subscribe(data=>{
    if(data===true)
      //do something use the data

  });
}

addIcons():Observable<boolean>{

  this.Service.getIcons().subscribe(icons => {

    return  return observableOf(true);   
  });

  return observableOf(false);   

}
Ashim
  • 877
  • 2
  • 12
  • 22

3 Answers3

7

You would use the of and switchMap operator from RxJS.

Your addIcons method becomes:

import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators'

ngOnInit() {
  this.addIcons().subscribe(data=>{
    if(data===true)
      //do something use the data

  });
}

addIcons():Observable<boolean>{
  return this.Service.getIcons().pipe(
    switchMap((response) =>{
      // do something with icons response
      // based on some condition return true or false
      return of(true)
    })
  )
}
C.OG
  • 6,236
  • 3
  • 20
  • 38
5
addIcons():Observable<boolean>{
  const result = new Subject<boolean>();

  this.Service.getIcons().subscribe(icons => {

    result.next(true);
    result.complete();
  },
  error => {
    result.next(false);
    result.complete();
  });   

  return result.asObservable();
}
alexander.sivak
  • 4,352
  • 3
  • 18
  • 27
1

Your addIcons() function always returns an observable of false. you first subscribe to getIcons() function, then returns the observableOf(false) and only then, the subscription occurs.

I'd do the following

private sub: Subscription;
ngOnInit() {
    this.sub = this.getIcons$()
        .subscribe(data => {
            if (data){
                //do something use the data
            }
    });
}

ngOnDestroy() {
    this.sub.unsubscribe();
}

getIcons$(): Observable<boolean> {
    return this.Service.getIcons()
        .pipe(
            map(icons => {
                return icons ? true : false
            })
        )
}

don't forget to unsubscribe the observable subscription otherwise you'll have memory leaks.

Ben Ari Kutai
  • 509
  • 3
  • 9