RxHttp&RxLife 交流群:378530627
友情提示: RxLife 与RxHttp搭配使用,味道更佳
RxLife 详细介绍:https://juejin.im/post/5cf3e1235188251c064815f1
Gradle 引用
dependencies {
implementation ‘com.rxjava.rxlife:rxlife:2.0.0’
//if you use AndroidX
implementation ‘com.rxjava.rxlife:rxlife-x:2.0.0’
}
注:由于官方对非 AndroidX 的库停止更新,故 rxlife 在 2.0.0 版本后也停止更新,后续将只更新 rxlife-x 版本,请尽快将项目迁移至 AndroidX
Usage
=====
1、Activity/Fragment
Activity/Fragment 销毁时,自动关闭 RxJava 管道
Observable.timer(5, TimeUnit.SECONDS)
.as(RxLife.as(this)) //此时的 this Activity/Fragment 对象
.subscribe(aLong -> {
Log.e(“LJX”, “accept =” + aLong);
});
2、View
View 被移除时,自动关闭 RxJava 管道
Observable.timer(5, TimeUnit.SECONDS)
.as(RxLife.as(this)) //此时的 this 为 View 对象
.subscribe(aLong -> {
Log.e(“LJX”, “accept =” + aLong);
});
3、ViewModel
Activity/Fragment 销毁时,自动关闭 RxJava 管道,ViewModel 需要继承ScopeViewModel
类,如下
public class MyViewModel extends ScopeViewModel {
public MyViewModel(@NonNull Application application) {
super(application);
}
public void test(){
Observable.interval(1, 1, TimeUnit.SECONDS)
.as(RxLife.asOnMain(this)) //继承 ScopeViewModel 后,就可以直接传 this
.subscribe(aLong -> {
Log.e(“LJX”, “MyViewModel aLong=” + aLong);
});
}
}
注意: 一定要在 Activity/Fragment 通过以下方式获取 ViewModel 对象,否则 RxLife 接收不到生命周期的回调
MyViewModel viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
4、任意类
Activity/Fragment 销毁时,自动关闭 RxJava 管道,任意类需要继承BaseScope
类,如 P 层:
public class Presenter extends BaseScope {
public Presenter(LifecycleOwner owner) {
super(owner); //添加生命周期监听
}
public void test(){
Observable.interval(1, 1, TimeUnit.SECONDS)
.as(RxLife.as(this)) //继承 BaseScope 后,就可以直接传 this
.subscribe(aLong -> {
Log.e(“LJX”, “accept aLong=” + aLong);
});
}
}
5、kotlin 用户
由于as
是 kotlin 中的一个关键字,所以在 kotlin 中,我们并不能直接使用as(RxLife.as(this))
,可以如下编写
Observable.intervalRange(1, 100, 0, 200, TimeUnit.MILLISECONDS)
.as
(RxLife.as
(this))
.subscribe { aLong ->
Log.e(“LJX”, “accept=” + aLong)
}
当然,相信没多少人会喜欢这种写法,故,RxLife 针对 kotlin 用户,新增更为便捷的写法,如下:
Observable.intervalRange(1, 100, 0, 200, TimeUnit.MILLISECONDS)
.life(this)
.subscribe { aLong ->
Log.e(“LJX”, “accept=” + aLong)
}
学习分享
在当下这个信息共享的时代,很多资源都可以在网络上找到,只取决于你愿不愿意找或是找的方法对不对了
很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘
如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。
2021最新上万页的大厂面试真题
七大模块学习资料:如NDK模块开发、Android框架体系架构…
只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。
由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示 。如有需要获取完整的资料文档的朋友点击我的GitHub免费获取。