Here is my TypeScript code utilizing 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));
I believe that the getParam function should return 'val' within an observable. However, I encounter an error with switchMap stating:
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 modify the getParam function to:
function getParam(val:any):Observable<any> {
return of(val).pipe(delay(1000))
}
It successfully returns 4
. So why does the from
operator not return an observable in this scenario?
Edit: This question is distinct from RxJs Observable of vs from because it focuses on the fact that both from
and of
should be observables. Yet, when using from
, switchMap
raises an issue about not receiving an observable and simply obtaining '1' from the array. I hope this clarifies the inquiry.