0

This is my TS code using RxJS:

function getParam(val:any):Observable<any> {
        return from(val).pipe(delay(1000))
    }

    of(1,2,3,4).pipe(
        switchMap(val => getParam(val))
    ).subscribe(val => console.log(val));

My understanding of the getParam function is, it will return 'val' wrapped in an observable. However, switchMap throws the following error:

hostReportError.js:5 Uncaught TypeError: You provided '1' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:39)
    at Module.from (from.js:15)
    at getParam (index.ts:6)
    at SwitchMapSubscriber.eval [as project] (index.ts:8)
    at SwitchMapSubscriber._next (switchMap.js:43)
    at SwitchMapSubscriber.Subscriber.next (Subscriber.js:63)
    at Observable.eval [as _subscribe] (subscribeToArray.js:7)
    at Observable._trySubscribe (Observable.js:50)
    at Observable.subscribe (Observable.js:36)
    at SwitchMapOperator.call (switchMap.js:27)

If I change the code of getParam to:

function getParam(val:any):Observable<any> {
    return of(val).pipe(delay(1000))
}

It returns 4 as expected. So why isn't from operator returning an observable in this case?

Edit: This is not a duplicate of RxJs Observable of vs from because I am not asking about the input arguments for from and of. My question is both from and of should both observables, yes? But when I use from, switchMap complains that it is NOT receiving an observable and it is just getting '1' from the array. Hope this clarifies.

  • `from` accepts an `ObservableInput` - an `Observable`, `Promise`, `Array` or iterable and emits the values 'contained' therein. `of` accepts and emits any value. – cartant Jun 04 '19 at 10:59
  • https://stackoverflow.com/questions/42704552/rxjs-observable-of-vs-from here is the answer – marsibarsi Jun 04 '19 at 11:36
  • Possible duplicate of [RxJs Observable of vs from](https://stackoverflow.com/questions/42704552/rxjs-observable-of-vs-from) – Sean Vieira Jun 04 '19 at 12:51
  • @cartant, `from` emits the "contained" values as an observable? If yes, then why switchMap isn't able to identify it as a stream? – Krishnan Ravikumar Jun 04 '19 at 14:11

1 Answers1

2

The error thrown not from switchMap
getParam(val: any) got a number so from() can't accept it as an input, but of() can


    hostReportError.js:5 Uncaught TypeError: 
      You provided '1' where a stream was expected. 
      You can provide an Observable, Promise, Array, or Iterable.
    at subscribeTo (subscribeTo.js:39)
    at Module.from (from.js:15)
Radik
  • 2,715
  • 1
  • 19
  • 24