一、在Android studio 项目添加Rxjava2.0
- 在build.gradle中添加 implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
- 点击右上角syne Now按钮
- 添加完成
二、简单使用Rxjava2.0
订阅一本正在更新中的小说
一本小说(xiaoshuo)(被观察者)
读者(duzhe)(观察者)
读者订阅了小说
功能代码实现(在按钮一中执行)
io.reactivex.Observable<String> xiaoshuo= io.reactivex.Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> e) throws Exception {
// 延时5秒发送数据
Thread.sleep(5000);
// 发送数据
e.onNext("更新一章");
// 关闭数据发送,无法再使用onNext();
e.onComplete();
}
});
io.reactivex.Observer<String> duzhe=new io.reactivex.Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
tv.setText("通知小说更新了");
}
@Override
public void onNext(String s) {
tv.setText(tv.getText()+"\n"+s);
}
@Override
public void onError(Throwable e) {
tv.setText("错误");
}
@Override
public void onComplete() {
tv.setText(tv.getText()+"\n"+"开始阅读");
}
};
// 读者订阅了小说
// 小说更新在子线程中,小说发生变化立刻通知读者
xiaoshuo.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(duzhe);
小说在子线程中更新,如主线程中更新会导致界面卡住5秒;
界面代码Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_1"
android:text="按钮一"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_2"
android:text="按钮二"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_3"
android:text="按钮三"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_4"
android:text="按钮四"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>