Отмена наблюдаемого промежуточного звена при невыполнении условия - PullRequest
3 голосов
/ 26 мая 2020

Можно ли отменить наблюдаемое в середине цепи? Предположим, у нас есть некая цепочка событий, которые зависят друг от друга, и если одна цепочка дает сбой, нет необходимости продолжать.

observable_1.pipe(
  take(1),
  switchMap((result_1) => {
    // Do something that requires observable_1 and return something
    // If it fails, there is no point to proceed
    // If it succeeds, we can continue
  }),
  switchMap((result_2) => {
    // Do something that requires result_2 and return something
    // If it fails, there is no point to proceed
    // If it succeeds, we can continue
  }),
  // etc...
);

Ответы [ 2 ]

2 голосов
/ 26 мая 2020

Таким образом, вы можете использовать для этой цели оператор filter :

observable_1.pipe(
      take(1),
      switchMap((result_1) => {
      }),
      switchMap((result_2) => {
        // If it fails, there is no point to proceed
        result_2.status = false;
        // If it succeeds, we can continue
        result_2.status = true;
        return result_2;
      }),
      filter(result => result.status)
      // etc...
    );
1 голос
/ 26 мая 2020

Похоже, вам нужно EMPTY.

observable_1.pipe(
  take(1),
  switchMap((result_1) => {
    // doing something
    if (successful) {
      return of(result_2);
    }
    return EMPTY; // no further emits.
  }),
  // we are here only in cases of result_2. EMPTY won't trigger it.
  switchMap((result_2) => {
    // doing something
    if (successful) {
      return of(result_3);
    }
    return EMPTY; // no further emits.
  }),
  // we are here only in cases of result_3. EMPTY won't trigger it.
);
...