declan roche
declan roche

Reputation: 99

returning rxjs function of type Observable<void>

I'm trying to convert the below observable code from using Observable.create to using pipeable operators.

public getUnrecoveredGearsAfterDep(): Observable<void> {

    return Observable.create((observer) => {      

      this.vesselDetailService.getVessel().subscribe(
        (vessel: Vessel) => {          
          console.log(vessel.cfr);
          this.getAndUpdateUnrecoveredGears(vessel.cfr).subscribe(
            () => {              
              observer.next(null);
              observer.complete();
            },
            (error) => {
              observer.error(error);
            }
          );
        },
        (error) => {
          observer.error(error);          
        }
      );    

    });
  }

I've tried the below method but I'm getting an conversion error cant convert type Observable.unknown to Observable.void any help would be appreciated.

public altGetUnrecoveredGearsAfterDep(): Observable<void> {

    return this.vesselDetailService.getVessel().pipe(
      tap( (vessel: Vessel) => console.log(vessel.cfr)),
      switchMap((vessel: Vessel) => this.getAndUpdateUnrecoveredGears(vessel.cfr)),
      map((gears: GearSet[]) => of())      
    );
  }

Upvotes: 8

Views: 6019

Answers (3)

Valerij Dobler
Valerij Dobler

Reputation: 2764

You could return it like that:

import { of } from 'rxjs';

public altGetUnrecoveredGearsAfterDep(): Observable<void> {
//...
    of(unit());
//...
}

function unit() {
  return void 0;
}

It worked for me in unit testing very well.

Upvotes: 0

BizzyBob
BizzyBob

Reputation: 14740

Your problem is that you are mapping your output to of() which is an observable. This gives your function a return type of Observable<Observable<never>>.

Your map should simply return undefined or null, you don't need of:

public altGetUnrecoveredGearsAfterDep(): Observable<void> {

    return this.vesselDetailService.getVessel().pipe(
      tap( (vessel: Vessel) => console.log(vessel.cfr)),
      switchMap((vessel: Vessel) => this.getAndUpdateUnrecoveredGears(vessel.cfr)),
      map((gears: GearSet[]) => undefined)      
    );
  }

Also, you could simplify by using mapTo and removing the type annotations:

public altGetUnrecoveredGearsAfterDep(): Observable<void> {

    return this.vesselDetailService.getVessel().pipe(
      tap(vessel => console.log(vessel.cfr)),
      switchMap(vessel => this.getAndUpdateUnrecoveredGears(vessel.cfr)),
      mapTo(undefined)      
    );
  }

Upvotes: 7

Yair Cohen
Yair Cohen

Reputation: 2258

At the end you are returning of(). The type of that value is Observable<unknown>, and it does not match the type in your return function Observable<void>.

To solve this you can simply return of(null).

Upvotes: 2

Related Questions