本文主要是介绍rxjava : lambda 与 ObservableTransformer 、compose:,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
示例一 : 将Integer 转 String
将一个发射整数的Observable转换为发射字符串的Observable。
// private ObservableTransformer<Integer, String> transformer() {
// return new ObservableTransformer<Integer, String>() {
// @Override
// public ObservableSource<String> apply(Observable<Integer> upstream) {
// return upstream.map(new Function<Integer, String>() {
// @Override
// public String apply(Integer integer) throws Exception {
// return String.valueOf(integer);
// }
// });
// }
// };
// }//简化// private ObservableTransformer<Integer, String> transformer() {
// return upstream -> upstream.map(new Function<Integer, String>() {
// @Override
// public String apply(Integer integer) throws Exception {
// return String.valueOf(integer);
// }
// });
// }//简化// private ObservableTransformer<Integer, String> transformer() {
// return upstream -> upstream.map((Function<Integer, String>) integer -> {
// return String.valueOf(integer);
// });
// }//简化private <String> ObservableTransformer<Integer, java.lang.String> transformer() {return upstream -> upstream.map((Function<Integer, java.lang.String>) java.lang.String::valueOf);
}
示例二 :线程切换
// public ObservableTransformer transformer2() {
// return new ObservableTransformer() {
// @Override
// public ObservableSource apply(Observable upstream) {
// return upstream.subscribeOn(Schedulers.io())
// .unsubscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread());
// }
// };
// }//简化public <T> ObservableTransformer<T, T> transformer2() {return upstream -> upstream.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
测试:
public class Test111111 {public void compose1() {Disposable disposable = Observable.just(123, 456).compose(transformer()).subscribe(s -> System.out.println("s: " + s));}public void compose2() {Disposable disposable = Observable.just(789, 321).compose(transformer2()).subscribe(integer -> System.out.println("integer===" + integer));}private <String> ObservableTransformer<Integer, java.lang.String> transformer() {return upstream -> upstream.map((Function<Integer, java.lang.String>) java.lang.String::valueOf);}public <T> ObservableTransformer<T, T> transformer2() {return upstream -> upstream.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());}
}
这篇关于rxjava : lambda 与 ObservableTransformer 、compose:的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!