'RxJs of operator for Observable<void>
I have a function that returns Observable<void> and I need it to return an observable that immediately emits and completes. Normally I would use the of operator to do this, but it doesn't work with void.
Things I've tried that don't work:
return of(); // doesn't emit
return of({}); // TypeScript compilation error 'Type 'Observable<{}>' is not assignable to type 'Observable<void>'.'
Things I've tried that do work, but I don't like:
return of({}).map(() => {}); // does extra work just to avoid compiler error
return of({}) as unknown as Observable<void>; // yucky casting
return new Observable<void>(s => {s.next(); s.complete();}); // verbose
I'm currently using the last one since it works without doing extra work, but I'd prefer a shortcut like of.
Solution 1:[1]
Solution 2:[2]
Short and simple: of(null) or of(undefined).
Solution 3:[3]
You can set generic type for operator of:
return of<void>(undefined);
or if you won't, do IIFE, like this way:
return of(((): void => {})());
Solution 4:[4]
You can also return EMPTY:
import { EMPTY, Observable } from "rxjs";
function test(): Observable<void> {
return EMPTY
}
test().subscribe(e => console.log("sub"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | martin |
| Solution 2 | |
| Solution 3 | Anton Marinenko |
| Solution 4 | Tobias S. |
