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

The never and throw operators

The empty operator was discussed in Chapter 3, Functional Programming with ReactiveX. This operator is one of a triplet of similar operators: empty, never, and throw. The behavior of each of these operators should be clear from their names, as follows:

  • The empty operator creates an empty observable that completes immediately
  • The never operator creates an observable that never completes
  • The throw operator creates an observable that immediately completes on error

The following figure shows the marble diagram of the never operator:

Figure 4.5: The never operator

The following figure shows the marble diagram of the throw operator:

Figure 4.6: The throw operator

Their prototypes are as follows:

Observable.never()
Observable.throw(exception, scheduler=None)

Note that the never operator does not have a scheduler parameter. Since it never emits anything, there is no need for scheduling! The throw operator accepts any object in the exception parameter. If the provided value is an exception, then it is sent as-is. If the provided value is not an exception, then this value is encapsulated in an exception object before being notified. So, the observer of this observable will always receive an exception in its on_error handler.

The following code shows two ways to use the throw operator:

error = Observable.throw("Something wrong happened")
error.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

exception = Observable.throw(NotImplementedError("I do nothing"))
exception.subscribe(
on_next=lambda i: print("item: {}".format(i)),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

The preceding code will provide the following results:

error: Something wrong happened
error: I do nothing
主站蜘蛛池模板: 高平市| 章丘市| 农安县| 莆田市| 乐山市| 榕江县| 徐水县| 广河县| 枣庄市| 南通市| 邯郸县| 奇台县| 富民县| 裕民县| 安顺市| 长葛市| 绥中县| 资溪县| 云梦县| 鲜城| 兴国县| 张北县| 临颍县| 志丹县| 和林格尔县| 阿克陶县| 永城市| 博乐市| 鄂温| 西丰县| 中牟县| 广饶县| 凭祥市| 陇南市| 车险| 锡林郭勒盟| 宣威市| 彭州市| 宜良县| 墨竹工卡县| 乐安县|