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

  • Learning RxJava
  • Thomas Nield
  • 203字
  • 2021-07-02 22:22:58

map()

For a given Observable<T>, the map() operator will transform a T emission into an R emission using the provided Function<T,R> lambda. We have already used this operator many times, turning strings into lengths. Here is a new example: we can take raw date strings and use the map() operator to turn each one into a LocalDate emission, as shown in the following code snippet:

import io.reactivex.Observable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Launcher {
public static void main(String[] args) {

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d
/yyyy"
);

Observable.just("1/3/2016", "5/9/2016", "10/12/2016")
.map(s -> LocalDate.parse(s, dtf))
.subscribe(i -> System.out.println("RECEIVED: " + i));
}
}

The output of the preceding code snippet is as follows:

RECEIVED: 2016-01-03
RECEIVED: 2016-05-09
RECEIVED: 2016-10-12

We passed a lambda that turns each string into a LocalDate object. We created a DateTimeFormatter in advance in order to assist with the LocalDate.parse() operation, which returns a LocalDate. In turn, we pushed each LocalDate emission to our Observer to be printed.

The map() operator does a one-to-one conversion for each emission. If you need to do a one-to-many conversion (turn one emission into several emissions), you will likely want to use flatMap() or concatMap(), which we will cover in the next chapter.

主站蜘蛛池模板: 东城区| 恩施市| 秦皇岛市| 晋城| 金溪县| 朝阳县| 五河县| 清丰县| 措美县| 新竹县| 蒙自县| 信宜市| 信宜市| 铁力市| 石嘴山市| 康定县| 宜兴市| 科技| 弥勒县| 招远市| 桃园市| 邻水| 凤台县| 密云县| 百色市| 鄂托克旗| 天全县| 宝坻区| 界首市| 乐至县| 阿巴嘎旗| 万宁市| 巩义市| 会宁县| 高青县| 同江市| 行唐县| 卓资县| 永丰县| 沂水县| 卢氏县|