Request的中断和ErrorHandler实例解析

  • Post category:Python
  1. Request的中断

在进行网络请求时,有时需要在某些条件下中断请求。这时可以使用RxJava的操作符takeUntil和takeWhile来实现。

  • takeUntil:当某条件成立时中断请求,例如:
Observable.interval(1, TimeUnit.SECONDS)
        .takeUntil(aLong -> aLong > 5) // 当aLong大于5时中断请求
        .subscribe(aLong -> System.out.println("takeUntil onNext: " + aLong),
                throwable -> System.out.println("takeUntil onError: " + throwable),
                () -> System.out.println("takeUntil onComplete"));
  • takeWhile:当某条件不成立时中断请求,例如:
Observable.interval(1, TimeUnit.SECONDS)
        .takeWhile(aLong -> aLong < 5) // 当aLong小于5时中断请求
        .subscribe(aLong -> System.out.println("takeWhile onNext: " + aLong),
                throwable -> System.out.println("takeWhile onError: " + throwable),
                () -> System.out.println("takeWhile onComplete"));
  1. ErrorHandler实例解析

RxJava提供了一个方便处理错误的类,即ErrorHandler。它可以为Observable或者Observer在遇到错误时提供一些处理机制。

RxJava提供了两个ErrorHandler的实现类:ResumeFunction和ResumeNextFunction。

  • ResumeFunction:捕获错误并发出一个新的Observable序列,例如:
Observable.create((ObservableOnSubscribe<String>) emitter -> {
    emitter.onNext("A");
    emitter.onNext("B");
    emitter.onError(new NullPointerException());
})
.onErrorResumeNext(throwable -> {
    System.out.println("ResumeFunction get error: " + throwable);
    return Observable.just("C", "D", "E");
})
.subscribe(s -> System.out.println("ResumeFunction onNext: " + s),
        throwable -> System.out.println("ResumeFunction onError: " +
                throwable.getLocalizedMessage()),
        () -> System.out.println("ResumeFunction onComplete"));

结果为:

ResumeFunction onNext: A
ResumeFunction onNext: B
ResumeFunction onNext: C
ResumeFunction onNext: D
ResumeFunction onNext: E
ResumeFunction onComplete
  • ResumeNextFunction:捕获错误并使用一个备用的Observable序列代替,例如:
Observable.create((ObservableOnSubscribe<String>) emitter -> {
    emitter.onNext("A");
    emitter.onNext("B");
    emitter.onError(new NullPointerException());
})
.onErrorResumeNext(new Function<Throwable, ObservableSource<? extends String>>() {
    @Override
    public ObservableSource<? extends String> apply(Throwable throwable) {
        System.out.println("ResumeNextFunction get error: " + throwable);
        return Observable.just("C", "D", "E");
    }
})
.subscribe(s -> System.out.println("ResumeNextFunction onNext: " + s),
        throwable -> System.out.println("ResumeNextFunction onError: " +
                throwable.getLocalizedMessage()),
        () -> System.out.println("ResumeNextFunction onComplete"));

结果为:

ResumeNextFunction onNext: C
ResumeNextFunction onNext: D
ResumeNextFunction onNext: E
ResumeNextFunction onComplete

在上面的代码中,当出现错误时,使用了一个备用序列来代替原本的序列,确保了流的正常执行。

本文只是对Request的中断和ErrorHandler实例进行简单介绍,实际应用中还可能需要更复杂的处理方式才能达到预期的结果。