distinct 去除重複數據
public static void test13() {
// 過濾重複的數據
List<Student> list = new ArrayList<>();
list.add(new Student("張三",18));
list.add(new Student("李四",18));
list.add(new Student("王五",18));
list.add(new Student("張三",28));
Observable
.from(list)
.distinct(new Func1<Student, String>() {
@Override
public String call(Student student) { // 這裏表示已學生的名字來作爲去重的判斷依據
return student.name;
}
})
.subscribe(new Action1<Student>() {
@Override
public void call(Student student) {
Log.v(TAG, "...call = " +student.name + " " + student.age);
}
});
}
Filter 過濾:
public static void test14(){
Observable
.range(1,9)
.filter(new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer integer) {
return integer > 5; // 大於5的數據纔打印
}
})
.subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
Log.v(TAG, "...call = " + integer);
}
});
}
first/last/eleelementAt() 過濾數據
public static void test15() {
// 過濾重複的數據
List<Student> list = new ArrayList<>();
list.add(new Student("張三",18));
list.add(new Student("李四",18));
list.add(new Student("王五",18));
list.add(new Student("張三",28));
Observable
.from(list)
.distinct(new Func1<Student, String>() {
@Override
public String call(Student student) {
return student.name;
}
})
// .first()
// .last()
.elementAt(1) // 根據索引 下標不能越界
.subscribe(new Action1<Student>() {
@Override
public void call(Student student) {
Log.v(TAG, "...call = " +student.name + " " + student.age);
}
});
}
take/takelast
public static void test16() {
// 過濾重複的數據
List<Student> list = new ArrayList<>();
list.add(new Student("張三",18));
list.add(new Student("李四",18));
list.add(new Student("王五",18));
list.add(new Student("張三",28));
Observable
.from(list)
// .take(2)
.takeLast(2) // 獲取數組最後兩個數據
.subscribe(new Action1<Student>() {
@Override
public void call(Student student) {
Log.v(TAG, "...call = " +student.name + " " + student.age);
}
});
}
Sample&IgnoreElements
Observable
.interval(1000, TimeUnit.MILLISECONDS)//每秒發送1個數字
.sample(2000,TimeUnit.MILLISECONDS)//每2秒採樣一次
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
Log.i(TAG, "call: "+aLong);
}
});輸出的是0 2 4 6 8......
Observable.just(1, 2, 3, 4, 1)
.ignoreElements()//不發送任何信息 直接發送onCompleted()
.subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
Log.i(TAG, "onCompleted: ");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer integer) {
Log.i(TAG, "onNext: "+integer);
}
});