1

How to subscribe on result of flatMap?

   timer(0, 2000)
      .pipe(
        flatMap(() => this.scannerService.scan(this.scanType)),
        takeWhile(res => res.errorDesc !== "SUCCESS")
      )
      .subscribe((res: IScanResponse) => {
});

I tried do use .subscribe() after pipe. But I get error as:

You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

My remote function is:

public scan(scanType: string): Observable<any> {}

My imports are:

import { timer } from "rxjs";
import { takeWhile } from "rxjs/operators";
import { ScannerService } from "src/app/api/ScannerService";
import { flatMap } from "rxjs/operators";
POV
  • 11,293
  • 34
  • 107
  • 201

2 Answers2

1

After the .pipe() since .pipe() returns an observable

const tm = timer(0, 2000).pipe(
     flatMap(() => this.scannerService.scan(this.scanType)),
     takeWhile(res => res)
).subscribe(res=> {
//your code
});;
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
  • It seems that he has already tried subscribe after the pipe. So his error is probably somewhere else. (Maybe a wrong import from another library than rxjs) – Wandrille Mar 17 '19 at 15:03
  • My import see in question please – POV Mar 17 '19 at 15:04
  • @OPV https://stackoverflow.com/questions/43549223/typeerror-you-provided-an-invalid-object-where-a-stream-was-expected-you-can-p/43549301 maybe this helps – Patricio Vargas Mar 17 '19 at 15:05
1

Your problem is your type returned by scan

In a flatMap, you need to return an Observable.

And here you return Observable<any> {} instead of just Observable<any>

Wandrille
  • 6,267
  • 3
  • 20
  • 43
  • Just add return key? – POV Mar 17 '19 at 15:08
  • It depends what you is the object. But yes, you can do something like : `.scan(..)[theKey]` – Wandrille Mar 17 '19 at 15:10
  • I really dont understand you, my scan function is: – POV Mar 17 '19 at 15:11
  • ``` public scan(scanType: string): Observable { return this.http.post(environment.scanService, { scanType: scanType }); } ``` – POV Mar 17 '19 at 15:12
  • If your scan function works like this, then it's good. No need for .scan(...)[key]. I though that your function return an object with an observable inside but no. – Wandrille Mar 17 '19 at 15:14