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
.
CodePudding user response:
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 => {})());
CodePudding user response:
You can also return EMPTY
:
import { EMPTY, Observable } from "rxjs";
function test(): Observable<void> {
return EMPTY
}
test().subscribe(e => console.log("sub"))