RxJava2 转换操作符

时间:2021-01-27 17:48:30

前言:

本文将在Rx官方解释的基础上,再融合其它国内讲解的文章。尽量用最简单的,易懂的方式,解释这些操作符。废话不多说,先列个表,把所有操作符列出来,再一 一做解释。解释的过程,以问答的形式(基于问题来学习),先从整体简单解释入手,并配上能跑的示例代码(0 warnings, 0 errors)。先知道能做什么和怎么做,再讲原理,并尽量做到中英融合解释。这是官方文档:Transforming Observables

一、需要了解的知识点:
Observer与Consumer的区别:后者是简化了前者,减去了许多回调接口。注意,重要的事说三遍:他们都是充当观察者角色他们都是充当观察者角色他们都是充当观察者角色。其它详情,可以参考这篇:Observer与Consumer的区别

二、配置RxJava2和RxAndroid
在项目的gradle里面的dependencies里加上这个

dependencies {
// RxJava2
implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
}

三、RxJava2转换操作符列表(A list of transforming operators of RxJava2):

  • map( ) 。 转换一组数据(任意类型)。转换流程是,先由Observable触发一个事件,就像Android里面的Click事件一样(但map的事件不是通过点击触发的,详情看map()一章)。 在android里面Click事件被触发后,会调用相应的void onClick方法。这里也是一样,会调用一个叫R apply(@NonNull T t)方法。。其中,T是原始类型,即被转换的类型。然后,该方法会返回一个泛型R。这个R,即是转换后的类型,具体什么类型,由你指定。 (transform the items emitted by an Observable by applying a function to each of them)
  • flatMap(), concatMap( ) and flatMapIterable( ) — transform the items emitted by an Observable into Observables (or Iterables), then flatten this into a single Observable
  • switchMap( ) — transform the items emitted by an Observable into Observables, and mirror those items emitted by the most-recently transformed Observable
  • scan( ) — apply a function to each item emitted by an Observable, sequentially, and emit each successive value
  • groupBy( ) — divide an Observable into a set of Observables that emit groups of items from the original Observable, organized by key
  • buffer( ) — periodically gather items from an Observable into bundles and emit these bundles rather than emitting the items one at a time
  • window( ) — periodically subdivide items from an Observable into Observable windows and emit these windows rather than emitting the items one at a time
  • cast( ) — cast all items from the source Observable into a particular type before reemitting them

截止2018/2/28 19:52,所有的转换操作符主要有上面这些,一共10个操作符。

下面是这些操作符对应的详细讲解地址(拆成多篇,看起来不会那么打击学习的士气):