Becoming more reactive with RxJS flatMap and switchMap

Building flatMap

const oddNumbers = [1, 3, 5]
const oneToSix = oddNumbers.map(x => [x, x + 1])
console.log(oneToSix) // -> [[ 1, 2], [3, 4], [5, 6]]
function flatten (arr) {
return arr.reduce((flatArr, subArray) => flatArr.concat(subArray), [])
}
const oneToSix = flatten(oddNumbers.map(x => [x, x + 1]))
console.log(oneToSix) // -> [1, 2, 3, 4, 5, 6]
function flatMap (arr, fn) {
return arr.reduce((flatArr, subArray) => flatArr.concat(fn(subArray)), [])
}
console.log(flatMap([1,3,5], x => [x, x + 1]))
// -> [1, 2, 3, 4, 5, 6]

Extending to observables

const second$ = Observable.interval(1000)
const response$ = Rx.Observable
.fromPromise(
fetch(‘https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699').then(response => response.json())
)
second$
.map(x => response$)
.subscribe(data => console.log(‘data is’, data))
// -> <huge mess>
second$
.flatMap(x => response$)
.subscribe(data => console.log(‘data is’, data))
// -> <JSON response data>

Switching to switchMap

const words = ‘Row row row your boat gently down the stream merrily merrily merrily merrily life is but a dream’.split(‘ ‘)const numWords = words.length
const singer$ = Rx.Observable
.Interval(500) // emit a value every half second
.scan(x => x + 1) // record the count
.map(count => count % numWords) // convert into a resetting index
.map(index => words[index]) // map to the word
singer$.subscribe(console.log)
const round$ = Rx.Observable
.interval(4500)
.flatMap(() => singer$)
round$.subscribe(console.log)
const brokenRecord$ = Rx.Observable
.interval(4500)
.switchMap(() => singer$)
brokenRecord$.subscribe(console.log)

Why this is useful

Creating a pauseable observable

const normalObservable$ = // any stream of data you want to pauseconst shouldObservableBePaused$ = // this is where your pausing logic goes — it should emit boolean values describing whether or not our data should be pausedconst pauseableObservable$ = shouldObservableBePaused$
.switchMap((pause) => pause ? Rx.Observable.never() : normalObservable$)

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to use Next.js <Image /> component

JavaScript Callbacks, Promises, Async Await in a nutshell

How to Reverse Arrays in JavaScript Without Using .reverse()

JavaScript Arrays

JavaScript

Create a GraphQL API Wrapper for your REST API

My Journey to DLithe Bootcamp(.NET Full Stack Week 3(Feb7- Feb12)

Be Careful of Passing an Async Function as a Parameter in JavaScript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Wilson

David Wilson

More from Medium

Typescript for Noobies

RxJs Observable vs Javascript Promise

The Array Prototype Naming Convention

TypeScript Enums: What they are and why you should avoid them