简体   繁体   中英

concatMap vs mergeMap with store Selector

I have spent many time learning difference between mergeMap and concatMap to clearly understand the differnce, and it' is clear to me now. I used good resources like https://rxjs-dev.firebaseapp.com and https://www.learnrxjs.io with other websites.

Both of this operators keeps the incoming source and subscribe to all emited values with difference in ordering. But in my project i have met a situation when using mergeMap and concatMap differs a lot to me, and i want to understand why.

Here is a code sample:

const Stream$ = from(requiredDocs.documents_type)
          .pipe(
            mergeMap(docID => this._store.select(selectDocumentTypeByID(docID))),
            scan((acc: Array<DocumentType | undefined>, curr) => {
              console.log('curr - ', curr)
              acc.push(curr)
              return acc
            }, [])
          ).subscribe(val => console.log(val))

Explanation : i am generating source from array requiredDocs.documents_type , then using values emitted to select from a store using selector - selectDocumentTypeByID(id: number) . The latter is a simple Array.find function that either returns undefined or a found object. Then i use scan rxjs operator to generate resulting Array of values from selector

Expected result: [ {obj}, {obj}, {obj} ] - three objects that are returned by select observable

mergeMap - result is as expected - [ {obj}, {obj}, {obj} ]

concatMap - result is just one obj(*first one*) - [ {obj} ]

If i change store selector to simple of(docID) rxjs operator it works as expected.

Why concatMap only returns one obj when using with store selector?

Yes, magic of question asking works except that for this time with lots of pain and thinking:) Answer is in concatMap definition. This operator subscribes to each outer source Observable and only subscribes to following when previous has been completed

Funny, how question came up in my head suddenly and kinda randomly:) After many hours of thinking about it. So, in order for my example to work properly i need to complete store.selector. Which i yet don't know how to do, but to me the difference between these two operatos is now clear which is a major thing.

mergeMap in its turn does not wait for source Observable to finish and this is why it works as i needed. Cheers all:)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM