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
);
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.
Observables are "lazy", meaning if no one is listening, nothing happens.
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.
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)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With