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

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.

主站蜘蛛池模板: 米易县| 康定县| 柳江县| 卓尼县| 南岸区| 沅江市| 南漳县| 澜沧| 镇康县| 乌兰察布市| 台北县| 泾阳县| 上栗县| 中方县| 通化县| 成武县| 大关县| 汉寿县| 达州市| 阿鲁科尔沁旗| 泸州市| 凤庆县| 蚌埠市| 全州县| 孝感市| 梧州市| 云和县| 六安市| 凉城县| 虎林市| 辽阳县| 洪洞县| 库伦旗| 鄂伦春自治旗| 高碑店市| 无锡市| 河津市| 兴义市| 镇江市| 高雄县| 郁南县|