Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable<void> usage pattern in Typescript

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 emitted when using Observable.of()
    (err: any) => console.error(err), // handle error state
    () => console.log('Success'),     // handle success state
  );
like image 742
Halt Avatar asked Sep 23 '17 10:09

Halt


People also ask

What is the use of observable in TypeScript?

An Observable is a collection of multiple input values that get processed using array methods such as map , reduce , filter , and so on. It comes in handy when handling asynchronous operations such as making HTTP requests, user-input events, and so on.

Why observable is lazy?

Observables are "lazy", meaning if no one is listening, nothing happens.

What is the difference between observable and promises?

The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.


1 Answers

Just to be more precise, when you define a Subject with generic type void there are two ways you can call its next() method and that is without any argument:

const subject = new Subject<void>();
subject.next();

...or with void 0:

subject.next(void 0);

In fact, the value argument to next is optional so if you don't specify it it'll send undefined which means that even if you have Subject<void> you'll still receive next notifications:

asyncFuncWithoutResult().subscribe(alawaysUndefined => {
  /* ... */
});

Also note that you can turn any Observable into <void> (this is necessary when you want to merge multiple Observables) by map or mapTo:

source.mapTo(void 0)
   ...
like image 171
martin Avatar answered Oct 12 '22 22:10

martin