Jack A.
Jack A.

Reputation: 4453

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.

Upvotes: 6

Views: 2515

Answers (4)

Kevin Baker
Kevin Baker

Reputation: 629

Short and simple: of(null) or of(undefined).

Upvotes: 4

martin
martin

Reputation: 96949

You can return of(void 0).

Live demo: https://stackblitz.com/edit/rxjs-yn6dmr

Upvotes: 3

Tobias S.
Tobias S.

Reputation: 23865

You can also return EMPTY:

import { EMPTY, Observable } from "rxjs";

function test(): Observable<void> {
  return EMPTY
}

test().subscribe(e => console.log("sub"))

Upvotes: 0

Anton Marinenko
Anton Marinenko

Reputation: 2992

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 => {})());

Upvotes: 2

Related Questions