Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJS: SwitchMap converts string into single characters unexpectedly

I am playing around with RXJS for TypeScript and stumbled upon an issue that I cannot explain myself. I have an observable that emits multiple strings. I then want to apply switchMap to it which is supposed to prepend "a" to each of those strings:

var o = Observable.create((observer) => {
    observer.next("hi")
    observer.next("bla")
})

o.switchMap(str => "a" + str).subscribe(str => console.log(str))

My expected output:

ahi
abla

Actual output:

a
h
i
a
b
l
a

So somewhere between switchMap and subscribe, the string gets broken down into characters apparently.

Can someone explain why this happens?

like image 249
fjc Avatar asked Mar 13 '17 17:03

fjc


2 Answers

I guess you meant to use map instead of switchMap.

switchMap actually expects an ObservableInput as return-value, which in your case is a string, which in turn is treated as an array and therefore split up into single elements.

To have your expected result with switchMap you could do:

o.switchMap(str => Observable.of("a" + str))
    .subscribe(str => console.log(str));

But better use:

o.map(str => "a" + str)
    .subscribe(str => console.log(str))

New syntax with pipe:

o.pipe(
    map(str => "a" + str)
).subscribe(str => console.log(str))
like image 182
olsn Avatar answered Nov 01 '22 15:11

olsn


I think you need map instead of switchMap.

The function passed to switchMap expects to return an observable or promise. "a" + str is not.

like image 2
Shawn Avatar answered Nov 01 '22 16:11

Shawn