Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice typing an Observable event with no value

I want to define a method returning an Observable but I don't have any data, what signature should I sue ?

myMethod(): Observable<null>;
myMethod(): Observable<void>;
myMethod(): Observable<{}>;

When coding the return in the method, I want to receive a next event in my first subscribe callback, so I can't use Observable.empty();

I could use the following :

myMethod(): Observable<null>; //I could use  return Observable.of(null);
myMethod(): Observable<void>; //I could use  return Observable.of(null);
myMethod(): Observable<{}>; //I could use  return Observable.of({});

I did not find an official way of doing it, but maybe there's a standard solution ... What is the best practice ?

like image 243
Gauthier Peel Avatar asked Apr 23 '18 10:04

Gauthier Peel


1 Answers

I think the best way is using myMethod(): Observable<void>; because null is still a valid value that is often used instead of an object for example. Also {} is an empty object (object with no properties).

You can emit values to void like this:

const s = new Subject<void>();
s.next();
s.next(void 0);

You can also map any existing Observable to Observable<void>:

source
  .pipe(
    mapTo(void 0),
  )
  ...
like image 87
martin Avatar answered Sep 28 '22 22:09

martin