K
K
Kot Matpockuh2018-12-10 18:32:34
JavaScript
Kot Matpockuh, 2018-12-10 18:32:34

RxJs: conditional mergeMap in pipe?

I have this amazing code:

this.myApi.getSomething(id).pipe(
    shop.isNew
        ? (
              map(tags => ({ ...updatedShop, tags })),
              mergeMap(() =>
                  this.myApi.addTags(updatedShop.id, shop.tags).pipe(
                      map(() => {
                          return {
                              ...updatedShop,
                              tags: shop.tags
                          };
                      })
                  )
              )
          )
        : map(tags => ({ ...updatedShop, tags }))
)

I can’t figure out how to make this work: if the condition is met, call the second service method and run `mergeMap` besides `map`, otherwise - only `map`
is it possible to implement somehow?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2018-12-10
@kot_matpockuh

// Да, сначала мы делаем map, потому что он делается полюбому:

let doSomething$ = this.myApi.getSomething(id).pipe(
  map(tags => ({ ...updatedShop, tags }))
)

// А затем мы делаем mergeMap если понадобится:

if (shop.isNew) {
  doSomething$ = doSomething$.pipe(
    mergeMap(() =>
                  this.myApi.addTags(updatedShop.id, shop.tags).pipe(
                      map(() => {
                          return {
                              ...updatedShop,
                              tags: shop.tags
                          };
                      })
                  )
              )
  )
}

// ну и затем подписываемся на это дело чтоб оно начало работать:

doSomething$.subscribe();

It will be much easier for you to understand RxJS after watching this video: https://www.youtube.com/watch?v=3LKMwkuK0ZE It is slightly behind the times (operators are now added to the browser via the pipe() function), but the principles themselves described in the video, do not go anywhere.
UPD
If the code above makes you sad, then you can do this:
this.myApi.getSomething(id).pipe(
  map(tags => ({ ...updatedShop, tags })),
  mergeMap((tags) => {
    if (!shop.isNew) {
      return of(tags);
    }
   return this.myApi.addTags(updatedShop.id, shop.tags).pipe(
                      map(() => {
                          return {
                              ...updatedShop,
                              tags: shop.tags
                          };
                      })
                  )
  }),
)

It means that you can take out the if in the mergeMap itself. And if the store is not new, then return the observation from the store, and if it is new, then do something else there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question