I am using flatMap
right now because it can process asynchronous code synchronously (as in one-by-one with values from previous result), but I do not know how it is doing this. The documentation doesn't seem to explain that this behavior is part of the operator.
On the RxJS doc flatMap
is defined as:
Projects each source value to an Observable which is merged in the output Observable.
I need to process a combination of observable
, promise
, and synchronous
code within my pipe. Most of the time piped data depends on its predecessor:
from(
// asyncrhonously fetch data from server
fetchDataAsync(credentials) // returns an Observable
).pipe(
flatMap((data) => {
// process the data with a promise
return from(processDataAsync(data))
}),
flatMap((data) => {
// sanitize the data with synchronous fn
return of(sanitizeDataSync(data))
}),
flatMap((data) => {
// store the data in local storage with a promise
return from(storeDataAsync(data))
})
)
flatMap
works, but I don't know how or why. How I can find this behavior in other operators?
Basically I want the benefit of observable streams that runs like your typical async function. What is the RX-way
of doing this?
async function fn() {
// asyncrhonously fetch data from server
const fetched = await fetchDataAsync(credentials).toPromise()
// process the data with a promise
const processed = await processDataAsync(fetched)
// sanitize the data with synchronous fn
const santized = sanitizeDataSync(processed)
// store the data in local storage with a promise
return await storeDataAsync(santized)
}
The flatMap
operator does not execute code sychronously: every time it receives an event of type Observable
, it subscribes to it and emits its events in the same returning Observable
. By the way it's been renamed to mergeMap
in the most recent versions, which describes its behavior better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.