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

distinct()

The distinct() operator will emit each unique emission, but it will suppress any duplicates that follow. Equality is based on hashCode()/equals() implementation of the emitted objects. If we wanted to emit the distinct lengths of a string sequence, it could be done as follows:

import io.reactivex.Observable;

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

Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
.map(String::length)
.distinct()
.subscribe(i -> System.out.println("RECEIVED: " + i));
}
}

The output of the preceding code snippet is as follows:

RECEIVED: 5
RECEIVED: 4
RECEIVED: 7

Keep in mind that if you have a wide, diverse spectrum of unique values, distinct() can use a bit of memory. Imagine that each subscription results in a HashSet that tracks previously captured unique values.

You can also add a lambda argument that maps each emission to a key used for equality logic. This allows the emissions, but not the key, to go forward while using the key for distinct logic. For instance, we can key off each string's length and use it for uniqueness, but emit the strings rather than their lengths:

import io.reactivex.Observable;

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

Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
.distinct(String::length)
.subscribe(i -> System.out.println("RECEIVED: " + i));
}
}

The output of the preceding code snippet is as follows:

RECEIVED: Alpha
RECEIVED: Beta
RECEIVED: Epsilon

Alpha is five characters, and Beta is four. Gamma and Delta were ignored because Alpha was already emitted and is 5 characters. Epsilon is seven characters, and because no seven-character string was emitted yet, it was emitted forward.

主站蜘蛛池模板: 读书| 凭祥市| 读书| 谢通门县| 浑源县| 漳平市| 巴中市| 丹巴县| 兰州市| 定襄县| 衡水市| 玉屏| 文化| 盘锦市| 承德市| 栾城县| 西盟| 罗甸县| 内江市| 色达县| 光山县| 东源县| 开化县| 安平县| 饶平县| 邻水| 宜春市| 陵水| 三门峡市| 中西区| 望江县| 山丹县| 拜泉县| 孟州市| 得荣县| 库尔勒市| 桂林市| 延安市| 正蓝旗| 徐州市| 苍南县|