Reputation: 2994
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
);
Upvotes: 22
Views: 15217
Reputation: 96949
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
:
source.pipe(map(() => void 0))
...
Upvotes: 27