2016-11-09 63 views
0

我想使用RxJavaAndroid应用程序中测试具有特定格式的QR码。我需要检查QR码的几种情况,如果属实,我需要停止进一步检查并对它们做出反应,例如,在UI中显示QR码无效的错误消息。RxJava过滤器并对事件做出反应?

我读到使用Observable.error不推荐,因为它只应用于极端事件,但我过滤的事件并不是极端,但可以预期,例如,扫描的QR码不是为我的应用程序创建的,或者QR码中包含的数据无效。否则,我会想到这样的事情:

Observable.just(barcode) 
       .doOnNext(new Action1<Barcode>() { 
        @Override 
        public void call(Barcode barcode) { 
         if(barcode.rawValue == null) { 
          throw new RuntimeException("empty"); 
         } 
         if(barcode.rawValue == null) { 
          throw new RuntimeException("empty"); 
         } 
        } 
       }) 
       .onErrorResumeNext(new Func1<Throwable, Observable<? extends Barcode>>() { 
        @Override 
        public Observable<? extends Barcode> call(Throwable throwable) { 
         //do something here 
        } 
       }) 
       .subscribe(new Subscriber<Barcode>() { 
        //update UI to show result 
       }); 

什么将是一个很好的实践来检验我对数据的条形码,而不流发送到onError()

回答

0

您可以引入一个单独的类型来描述Barcode扫描结果。即

class BarcodeScanningResult { 
    Barcode barcode; 
    String error; 
    public BarcodeScanningResult(Barcode barcode, String error) { 
     this.barcode = barcode; 
     this.error = error; 
    } 
} 

,然后使用它:

Observable.just(barcode) 
    .map(new Func1<Barcode, BarcodeScanningResult>() { 
     @Override 
     public BarcodeScanningResult call(Barcode barcode) { 
      if(barcode.rawValue == null) { 
       return new BarcodeScanningResult(barcode, "empty") 
      } 
      if(barcode.rawValue.trim().length == 0) { 
       return new BarcodeScanningResult(barcode, "blank"); 
      } 
      return new BarcodeScanningResult(barcode) 
     } 
    }).subscribe(new Subscriber<BarcodeScanningResult>() { 

})