RxJava2 / RxAndroid2操作符ofType:根据类型选择输出结果
例如:
package zhangphil.app;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
private Object[] test_data = {
1, "zhang", 2, 3, "phil", 5, 5, 6, 7, 7, 8, 9
}; // 故意设置若干重复的数据,等待去重复数据
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
test();
}
private void test() {
DisposableObserver disposableObserver = new DisposableObserver<Object>() {
@Override
public void onNext(Object o) {
Log.d(TAG, "#####开始#####");
Log.d("数据", String.valueOf(o));
Log.d(TAG, "#####结束#####");
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete");
}
@Override
public void onError(Throwable e) {
Log.e(TAG, e.toString(), e);
}
};
Observable<Object> observable = Observable.fromArray(test_data);
mCompositeDisposable.add(observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.ofType(String.class) //只显示字符串类型
.subscribeWith(disposableObserver));
}
@Override
protected void onDestroy() {
super.onDestroy();
// 如果退出程序,就清除后台任务
mCompositeDisposable.clear();
}
}
输出:
05-18 10:28:43.170 14762-14762/zhangphil.app D/MainActivity: #####开始#####
05-18 10:28:43.170 14762-14762/zhangphil.app D/数据: zhang
05-18 10:28:43.170 14762-14762/zhangphil.app D/MainActivity: #####结束#####
05-18 10:28:43.170 14762-14762/zhangphil.app D/MainActivity: #####开始#####
05-18 10:28:43.170 14762-14762/zhangphil.app D/数据: phil
05-18 10:28:43.170 14762-14762/zhangphil.app D/MainActivity: #####结束#####
05-18 10:28:43.171 14762-14762/zhangphil.app D/MainActivity: onComplete
结果如预期,只输出字符串类型的数据。