RxJava2 和 RxJava1 的變化

WIKI


Operator differences


Most operators are still there in 2.x and practically all of them have the same behavior as they had in 1.x. The following subsections list each base reactive type and the difference between 1.x and 2.x.

Generally, many operators gained overloads that now allow specifying the internal buffer size or prefetch amount they should run their upstream (or inner sources).

Some operator overloads have been renamed with a postfix, such as fromArray, fromIterable etc. The reason for this is that when the library is compiled with Java 8, the javac often can't disambiguate between functional interface types.

Operators marked as @Beta or @Experimental in 1.x are promoted to standard.


1.x Observable to 2.x Flowable


Factory methods:

1.x 2.x
amb added amb(ObservableSource...) overload, 2-9 argument versions dropped
RxRingBuffer.SIZE bufferSize()
combineLatest added varargs overload, added overloads with bufferSize argument, combineLatest(List) dropped
concat added overload with prefetch argument, 5-9 source overloads dropped, use concatArray instead
N/A added concatArray and concatArrayDelayError
N/A added concatArrayEager and concatArrayEagerDelayError
concatDelayError added overloads with option to delay till the current ends or till the very end
concatEagerDelayError added overloads with option to delay till the current ends or till the very end
create(SyncOnSubscribe) replaced with generate + overloads (distinct interfaces, you can implement them all at once)
create(AsnycOnSubscribe) not present
create(OnSubscribe) repurposed with safe create(FlowableOnSubscribe, BackpressureStrategy), raw support via unsafeCreate()
from disambiguated into fromArray, fromIterable, fromFuture
N/A added fromPublisher
fromAsync renamed to create()
N/A added intervalRange()
limit dropped, use take
merge added overloads with prefetch
mergeDelayError added overloads with prefetch
sequenceEqual added overload with bufferSize
switchOnNext added overload with prefetch
switchOnNextDelayError added overload with prefetch
timer deprecated overloads dropped
zip added overloads with bufferSize and delayErrors capabilities, disambiguated to zipArray and zipIterable

Instance methods:

1.x 2.x
all RC3 returns Single<Boolean> now
any RC3 returns Single<Boolean> now
asObservable renamed to hide(), hides all identities now
buffer overloads with custom Collection supplier
cache(int) deprecated and dropped
collect RC3 returns Single<U>
collect(U, Action2<U, T>) disambiguated to collectInto and RC3 returns Single<U>
concatMap added overloads with prefetch
concatMapDelayError added overloads with prefetch, option to delay till the current ends or till the very end
concatMapEager added overloads with prefetch
concatMapEagerDelayError added overloads with prefetch, option to delay till the current ends or till the very end
count RC3 returns Single<Long> now
countLong dropped, use count
distinct overload with custom Collection supplier.
doOnCompleted renamed to doOnComplete, note the missing d !
doOnUnsubscribe renamed to Flowable.doOnCancel and doOnDispose for the others, additional info
N/A added doOnLifecylce to handle onSubscribe, request and cancel peeking
elementAt(int) RC3 no longer signals NoSuchElementException if the source is shorter than the index
elementAt(Func1, int) dropped, use filter(predicate).elementAt(int)
elementAtOrDefault(int, T) renamed to elementAt(int, T) and RC3 returns Single<T>
elementAtOrDefault(Func1, int, T) dropped, use filter(predicate).elementAt(int, T)
first() RC3 renamed to firstElement and returns Maybe<T>
first(Func1) dropped, use filter(predicate).first()
firstOrDefault(T) renamed to first(T) and RC3 returns Single<T>
firstOrDefault(Func1, T) dropped, use filter(predicate).first(T)
flatMap added overloads with prefetch
N/A added forEachWhile(Predicate<T>, [Consumer<Throwable>, [Action]]) for conditionally stopping consumption
groupBy added overload with bufferSize and delayError option, the custom internal map version didn't make it into RC1
ignoreElements RC3 returns Completable
isEmpty RC3 returns Single<Boolean>
last() RC3 renamed to lastElement and returns Maybe<T>
last(Func1) dropped, use filter(predicate).last()
lastOrDefault(T) renamed to last(T) and RC3 returns Single<T>
lastOrDefault(Func1, T) dropped, use filter(predicate).last(T)
nest dropped, use manual just
publish(Func1) added overload with prefetch
reduce(Func2) RC3 returns Maybe<T>
N/A added reduceWith(Callable, BiFunction) to reduce in a Subscriber-individual manner, returns Single<T>
N/A added repeatUntil(BooleanSupplier)
repeatWhen(Func1, Scheduler) dropped the overload,use subscribeOn(Scheduler).repeatWhen(Function) instead
retry added retry(Predicate), retry(int, Predicate)
N/A added retryUntil(BooleanSupplier)
retryWhen(Func1, Scheduler) dropped the overload, use subscribeOn(Scheduler).retryWhen(Function) instead
sample doesn't emit the very last item if the upstream completes within the period,added overloads with emitLast parameter
N/A added scanWith(Callable, BiFunction) to scan in a Subscriber-individual manner
single() RC3 renamed to singleElement and returns Maybe<T>
single(Func1) dropped, use filter(predicate).single()
singleOrDefault(T) renamed to single(T) and RC3 returns Single<T>
singleOrDefault(Func1, T) dropped, use filter(predicate).single(T)
skipLast added overloads with bufferSize and delayError options
startWith 2-9 argument version dropped, use startWithArray instead
N/A added startWithArray to disambiguate
N/A added subscribeWith that returns its input after subscription
switchMap added overload with prefetch argument
switchMapDelayError added overload with prefetch argument
takeLastBuffer dropped
N/A added test() (returns TestSubscriber subscribed to this) with overloads to fluently test
throttleLast doesn't emit the very last item if the upstream completes within the period, use sample with the emitLast parameter
timeout(Func0<Observable>, ...) signature changed to timeout(Publisher, ...) and dropped the function, use defer(Callable<Publisher>>) if necessary
toBlocking().y inlined as blockingY() operators, except toFuture
toCompletable RC3 dropped, use ignoreElements
toList RC3 returns Single<List<T>>
toMap RC3 returns Single<Map<K, V>>
toMultimap RC3 returns Single<Map<K, Collection<V>>>
N/A added toFuture
N/A added toObservable
toSingle RC3 dropped, use single(T)
toSortedList RC3 returns Single<List<T>>
withLatestFrom 5-9 source overloads dropped
zipWith added overloads with prefetch and delayErrors options

Different return types

  • Some operators that produced exactly one value or an error now return Single in 2.x (or Maybe if an empty source is allowed).
  • (Remark: this is "experimental" in RC2 and RC3 to see how it feels to program with such mixed-type sequences and whether or not there has to be too much toObservable/toFlowable back-conversion.)
Operator Old return type New return type Remark
all(Predicate) Observable<Boolean> Single<Boolean> Emits true if all elements match the predicate
any(Predicate) Observable<Boolean> Single<Boolean> Emits true if any elements match the predicate
count() Observable<Long> Single<Long> Counts the number of elements in the sequence
elementAt(int) Observable<T> Maybe<T> Emits the element at the given index or completes
elementAt(int, T) Observable<T> Single<T> Emits the element at the given index or the default
elementAtOrError(int) Observable<T> Single<T> Emits the indexth element or a NoSuchElementException
first(T) Observable<T> Single<T> Emits the very first element or NoSuchElementException
firstElement() Observable<T> Maybe<T> Emits the very first element or completes
firstOrError() Observable<T> Single<T> Emits the first element or a NoSuchElementException if the source is empty
ignoreElements() Observable<T> Completable Ignore all but the terminal events
isEmpty() Observable<Boolean> Single<Boolean> Emits true if the source is empty
last(T) Observable<T> Single<T> Emits the very last element or the default item
lastElement() Observable<T> Maybe<T> Emits the very last element or completes
lastOrError() Observable<T> Single<T> Emits the lastelement or a NoSuchElementException if the source is empty
reduce(BiFunction) Observable<T> Maybe<T> Emits the reduced value or completes
reduce(Callable, BiFunction) Observable<U> Single<U> Emits the reduced value (or the initial value)
reduceWith(U, BiFunction) Observable<U> Single<U> Emits the reduced value (or the initial value)
single(T) Observable<T> Single<T> Emits the only element or the default item
singleElement() Observable<T> Maybe<T> Emits the only element or completes
singleOrError() Observable<T> Single<T> Emits the one and only element, IndexOutOfBoundsException if the source is longer than 1 item or a NoSuchElementException if the source is empty
toList() Observable<List<T>> Single<List<T>> collects all elements into a List
toMap() Observable<Map<K, V>> Single<Map<K, V>> collects all elements into a Map
toMultimap() Observable<Map<K, Collection<V>>> Single<Map<K, Collection<V>>> collects all elements into a Map with collection
toSortedList() Observable<List<T>> Single<List<T>> collects all elements into a List and sorts it

Removals

  • To make sure the final API of 2.0 is clean as possible, we remove methods and other components between release candidates without deprecating them.
Removed in version Component Remark
RC3 Flowable.toCompletable() use Flowable.ignoreElements()
RC3 Flowable.toSingle() use Flowable.single(T)
RC3 Flowable.toMaybe() use Flowable.singleElement()
RC3 Observable.toCompletable() use Observable.ignoreElements()
RC3 Observable.toSingle() use Observable.single(T)
RC3 Observable.toMaybe() use Observable.singleElement()

Miscellaneous changes


doOnCancel/doOnDispose/unsubscribeOn


In 1.x, the doOnUnsubscribe was always executed on a terminal event because 1.x' SafeSubscriber called unsubscribe on itself. This was practically unnecessary and the Reactive-Streams specification states that when a terminal event arrives at a Subscriber, the upstream Subscription should be considered cancelled and thus calling cancel() is a no-op.

For the same reason, unsubscribeOn is not called on the regular termination path but only when there is an actual cancel (or dispose) call on the chain.

Therefore, the following sequence won't call doOnCancel:

Flowable.just(1, 2, 3)
.doOnCancel(() -> System.out.println("Cancelled!"))
.subscribe(System.out::println);

However, the following will call since the take operator cancels after the set amount of onNext events have been delivered:

Flowable.just(1, 2, 3)
.doOnCancel(() -> System.out.println("Cancelled!"))
.take(2)
.subscribe(System.out::println);

If you need to perform cleanup on both regular termination or cancellation, consider the operator using instead.

Alternatively, the doFinally operator (introduced in 2.0.1 and standardized in 2.1) calls a developer specified Action that gets executed after a source completed, failed with an error or got cancelled/disposed:

Flowable.just(1, 2, 3)
.doFinally(() -> System.out.println("Finally"))
.subscribe(System.out::println);

Flowable.just(1, 2, 3)
.doFinally(() -> System.out.println("Finally"))
.take(2) // cancels the above after 2 elements
.subscribe(System.out::println);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市假栓,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件仑最,死亡現(xiàn)場離奇詭異玷过,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)勤篮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來色罚,“玉大人碰缔,你說我怎么就攤上這事〈粱ぃ” “怎么了金抡?”我有些...
    開封第一講書人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長腌且。 經(jīng)常有香客問我梗肝,道長,這世上最難降的妖魔是什么铺董? 我笑而不...
    開封第一講書人閱讀 58,204評(píng)論 1 292
  • 正文 為了忘掉前任巫击,我火速辦了婚禮,結(jié)果婚禮上精续,老公的妹妹穿的比我還像新娘坝锰。我一直安慰自己,他們只是感情好重付,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評(píng)論 6 388
  • 文/花漫 我一把揭開白布顷级。 她就那樣靜靜地躺著,像睡著了一般确垫。 火紅的嫁衣襯著肌膚如雪愕把。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,190評(píng)論 1 299
  • 那天森爽,我揣著相機(jī)與錄音恨豁,去河邊找鬼。 笑死爬迟,一個(gè)胖子當(dāng)著我的面吹牛橘蜜,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼计福,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼跌捆!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起象颖,我...
    開封第一講書人閱讀 38,923評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤佩厚,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后说订,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體抄瓦,經(jīng)...
    沈念sama閱讀 45,334評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評(píng)論 2 333
  • 正文 我和宋清朗相戀三年陶冷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了钙姊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,727評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡埂伦,死狀恐怖煞额,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情沾谜,我是刑警寧澤膊毁,帶...
    沈念sama閱讀 35,428評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站基跑,受9級(jí)特大地震影響婚温,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜涩僻,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望栈顷。 院中可真熱鬧逆日,春花似錦、人聲如沸萄凤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽靡努。三九已至坪圾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間惑朦,已是汗流浹背兽泄。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留漾月,地道東北人病梢。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蜓陌。 傳聞我的和親對(duì)象是個(gè)殘疾皇子觅彰,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容