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

  • Learning RxJava
  • Thomas Nield
  • 271字
  • 2021-07-02 22:22:57

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.

主站蜘蛛池模板: 和林格尔县| 曲靖市| 荥经县| 陕西省| 凤山县| 射洪县| 景德镇市| 晋中市| 运城市| 昌平区| 东源县| 青河县| 湘乡市| 仁寿县| 韩城市| 临漳县| 东乡| 石屏县| 隆尧县| 岳普湖县| 响水县| 长岛县| 永安市| 尼勒克县| 红原县| 仪征市| 图木舒克市| 长治县| 随州市| 台北县| 永州市| 朔州市| 卓尼县| 新竹市| 东乌珠穆沁旗| 阿瓦提县| 屯留县| 南华县| 七台河市| 延吉市| 乡城县|