samedi 23 septembre 2017

Observable

When an async service has no return value but I want to use Observables I'm inclined to use Observable<boolean>. But I don't have meaning for this boolean value because the service either fails or succeeds and if it fails I want the Observable to be in the error state. This leaves only 'true' values for the observed boolean.

Is the following use of Observable<void> a good pattern for these situations? Or are there foreseeable problems with the use of Observable<void>

const asyncFuncWithoutResult = (): Observable<void> => {
  // fake something async that has no return value

  const itWorked = true; // or not
  if (itWorked) {
    return Observable.of();
  } else {
    return Observable.throw(Error('It did not work'));
  }
}

// call the service
asyncFuncWithoutResult()
  .subscribe(
    undefined, // nothing will be emited when using Observable.of()
    (err: any) => console.error(err), // handle error state
    () => console.log('Success'),     // handle success state
  );

Aucun commentaire:

Enregistrer un commentaire