直接上代码
public class RxLifeActivity extends RxAppCompatActivity {
/**
* RxLifecycle使用:在当前activity中继承RxAppCompatActivity
* <p>
* ActivityEvent:手动设置指定在什么时候取消订阅,下列枚举
* CREATE,
* START,
* RESUME,
* PAUSE,
* STOP,
* DESTROY
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rx_life);
Flowable.interval(3, 2, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.compose(this.bindUntilEvent(ActivityEvent.PAUSE)) //手动设置在activity onPause的时候取消订阅
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> Log.e("liuqiang", "RxLifeActivityOnCreate:" + aLong));
}
@Override
protected void onStart() {
super.onStart();
Flowable.interval(6, 3, TimeUnit.SECONDS)
//bindToLifecycle的自动取消订阅示例,因为是在onStart的时候调用,所以在onStop的时候自动取消订阅
.compose(this.bindToLifecycle()) //设置在默认的生命周期中取消订阅
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> Log.e("liuqiang", "RxLifeActivityOnStart:" + aLong));
}
}