Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

RxJS 如何出错后不自动取消订阅?

假设有如下代码模拟我目前的环境,
在线查看地址:https://stackblitz.com/edit/r...

import { of, BehaviorSubject } from 'rxjs'; 
import { switchMap, map, catchError, tap } from 'rxjs/operators';

/**
 * 模拟通过http请求获取数据
 */
function getData(value) {
  return of(value)
    .pipe(map(value => {
      // 模拟http请求报错
      if(value % 2 === 0) {
        throw new Error('不是奇数');
      }
      return value;
    }));
}

const subject = new BehaviorSubject<number>(1);

subject
  .pipe(switchMap(value => {
    return getData(value);
  }))
  .pipe(tap(value => console.log(value)))
  .pipe(catchError(err => {
    console.error(err);
    return of(null);
  }))
  .subscribe();

for(let i of [3 ,5 ,7 ,9 ,10, 11, 13, 15, 17]) {
  subject.next(i);
}

上面的代码在运行的时候输出如下:
image.png

我使用getData函数模拟http请求,假如http请求出错,如何不取消当前subject的订阅?即继续处理后续11, 13, 15, 17这些数据,我使用了catchError但是不生效。


目前已知的一个解决方法是把pipe放到switchMap里面,但是这样嵌套很不美观,求其他解决方式?

subject
  .pipe(switchMap(value => {
    return getData(value)
      .pipe(tap(value => console.log(value)))
      .pipe(catchError(err => {
        console.error(err);
        return of(null);
      }))
  }))
  .subscribe();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

https://stackblitz.com/edit/r...

你可以把catchError放到getData中使用,这样就不会中断后面的后续的流了.

function getData(value) {
  return of(value).pipe(
    map(value => {
      // 模拟http请求报错
      if (value % 2 === 0) {
        throw new Error("不是奇数");
      }
      return value;
    }),
    catchError(err => {
      console.error(err);
      return of(null);
    })
  );
}

const subject = new BehaviorSubject<number>(1);

subject
  .pipe(
    switchMap(value => {
      return getData(value);
    }),
    filter(v=>!!v), // 增加一个 filte 过滤空值
    tap(value => console.log(value))
  )
  .subscribe();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...