官术网_书友最值得收藏!

Catch

The use of onError gives us a much better experience overall, but it isn't very flexible.

Let's imagine a different scenario, where we have an observable retrieving data from the network. What if, when this observer fails, we would like to present the user with a cached value instead of an error message?

This is where the catch combinator comes in. It allows us to specify a function to be invoked when the observable throws an exception, much like OnError does.

Differently from OnError, however, catch has to return a new observable that will be the new source of items from the moment the exception was thrown:

(rx/subscribe (->> (exceptional-obs) 
                   (rx/catch Exception e 
                       (rx/return 10)) 
                   (rx/map inc)) 
              (fn [v] (prn-to-repl "result is " v))) 
 
;; "result is " 11 

In the previous example, we are essentially specifying that, whenever exceptional-obs throws, we should return the value 10. We are not limited to single values, however. In fact, we can use any observable we like as the new source:

(rx/subscribe (->> (exceptional-obs) 
                   (rx/catch Exception e 
                     (rx/seq->o (range 5))) 
                   (rx/map inc)) 
              (fn [v] (prn-to-repl "result is " v))) 
 
;; "result is " 1 
;; "result is " 2 
;; "result is " 3 
;; "result is " 4 
;; "result is " 5 
主站蜘蛛池模板: 县级市| 惠安县| 天津市| 河东区| 兴山县| 富平县| 龙游县| 永定县| 石狮市| 通山县| 郸城县| 巴南区| 崇阳县| 正阳县| 邵阳市| 普定县| 巴青县| 亚东县| 天峨县| 郯城县| 中方县| 台前县| 平潭县| 八宿县| 绍兴县| 务川| 台中县| 板桥市| 三江| 巧家县| 微山县| 锡林浩特市| 友谊县| 屏东市| 肇庆市| 沧州市| 岚皋县| 于都县| 怀化市| 大同县| 木兰县|