本文使用eclipse編輯器,gradle依賴jar,如若未配置此環(huán)境谣殊,請轉Java Eclipse配置gradle編譯項目配置好環(huán)境后再查看此文
- 創(chuàng)建Gradle(STS) Project工程莱褒,并刪除其他一些不需要的文件提佣。
在build.gradle文件的dependencies中依賴,并刷新依賴肚吏。
compile "io.reactivex.rxjava2:rxjava:2.1.3"
創(chuàng)建一個Client.java類方妖,實現main方法狭魂。接下來開始使用RxJava罚攀。
創(chuàng)建一個simple方法,該方法簡單的使用RxJava.
/**
* 簡單使用
*/
public static void simple() {
Flowable//流
.just("one") //數據
.subscribe(new Consumer<String>() {//訂閱一個消費者
public void accept(String t) throws Exception {
System.out.println(t); // 打印數據
}
});
}
輸出為:
one
- 不同線程的調度雌澄,切換線程斋泄,不同線程中傳遞數據。
/**
* 線程示例
* @throws InterruptedException
*/
public static void threadSimple() throws InterruptedException {
Flowable//流
.fromCallable(new Callable<String>() {//子線程調用
public String call() throws Exception {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
return "true";
}
})
.subscribeOn(Schedulers.io())//io線程
.observeOn(Schedulers.single())//單線程
.subscribe(new Consumer<String>() {//主線程訂閱
public void accept(String t) throws Exception {
System.out.println(Thread.currentThread().getName());
System.out.println(t);
}
}, new Consumer<Throwable>() {
public void accept(Throwable t) throws Exception {
System.out.println(t);
}
});
Thread.sleep(2000);
}
打印結果:
RxCachedThreadScheduler-1
RxSingleScheduler-1
true
3.實現1-10數字的自乘镐牺。
/**
* map使用
*/
public static void mapSimple() {
Flowable//流
.range(1, 10)//從1到10
.observeOn(Schedulers.computation())//用于計算工作的實例
.map(new Function<Integer, Integer>() {//對每一項進行自乘
public Integer apply(Integer t) throws Exception {
return t*t;
}
})
.blockingSubscribe(new Consumer<Integer>() {//當前線程回調
public void accept(Integer t) throws Exception {
System.out.println(t);
}
});
}
打印結果:
1
4
9
16
25
36
49
64
81
100
- 實現1-10自乘炫掐,亂序打印。
/**
* flatMap使用
*/
public static void flatMapSimple() {
Flowable
.range(1, 10)
.flatMap(new Function<Integer, Publisher<? extends Integer>>() {
public Publisher<? extends Integer> apply(Integer t) throws Exception {
return Flowable
.just(t)
.subscribeOn(Schedulers.computation())
.map(new Function<Integer, Integer>() {
public Integer apply(Integer t) throws Exception {
return t*t;
}
});
}
})
.blockingSubscribe(new Consumer<Integer>() {
public void accept(Integer t) throws Exception {
System.out.println(t);
}
});
}
打印結果:
9
16
25
36
49
64
1
4
81
100
- 從2.0.5開始睬涧,有一個“實驗”操作符的并行和“平行流”募胃,有助于實現相同的并行處理模式。
/**
* 平行調用map
*/
public static void parallelSimple() {
Flowable
.range(1, 10)
.parallel()//平行
.runOn(Schedulers.computation())
.map(new Function<Integer, Integer>() {
public Integer apply(Integer t) throws Exception {
return t*t;
}
})
.sequential()//順序
.blockingSubscribe(new Consumer<Integer>() {
public void accept(Integer t) throws Exception {
System.out.println(t);
}
});
}
打印結果:
1
4
9
16
25
36
49
64
81
100