When dealing with an async service that does not have a return value but requires the use of Observables, I often find myself using Observable<boolean>
. However, in reality, I do not need to assign any meaning to this boolean value because the service either fails or succeeds. If it fails, I want the Observable to be in the error state, leaving only 'true' values for observation.
Is utilizing Observable<void>
a suitable pattern for such scenarios? Are there any potential issues with using Observable<void>
?
const asyncFuncWithoutResult = (): Observable<void> => {
// Simulate an asynchronous operation with 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
);