android订阅管理,RXJAVA取消订阅封装-kotlin-Android
因為好幾次自己想要在別的項目使用,每次都要重寫一遍太麻煩,整理了一下發(fā)布到 jcenter 。
利用官方lifecycle庫與kotlin語言特性。lifecycle官方 support 27+ 自帶。
庫代碼數(shù)少于100行。
用法:
1、添加依賴
implementation 'com.sjianjun:rxutils:1.0.2'
2、代碼
提供了3個Disposable的擴展方法這里使用destory演示。
class MainActivity : AppCompatActivity(), AutoDisposeEnhance {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//
Observable.create { }.doOnDispose {
Log.e("dispose", Exception("測試檢查調(diào)用棧"))
}.subscribe().destroy(lifecycle = lifecycle)
//destroy 方法的參數(shù)由 接口 sjj.rx.AutoDisposeEnhance 提供 。
Observable.create { }.doOnDispose {
Log.e("dispose2", Exception("測試檢查調(diào)用棧"))
}.subscribe().destroy()
}
override fun onResume() {
super.onResume()
}
}
說明
interface AutoDisposeEnhance {
fun Disposable.destroy(onceKey: String? = null) {
destroy(onceKey, getLifecycle())
}
fun Disposable.stop(onceKey: String? = null) {
stop(onceKey, getLifecycle())
}
fun Disposable.pause(onceKey: String? = null) {
pause(onceKey, getLifecycle())
}
fun getLifecycle():Lifecycle
}
主要聲明了三個方法擴展destory、stop、pause
參數(shù): oncekey , 如果重復的話會直接取消之前的disposeable 如果為null 則不處理
參數(shù):lifecycle ,被綁定到的聲明周期對象,通常由 activity 或者 fragment 提供,也可以自定義。
destory stop pause 三個擴展方法,表示在相應的生命周期 取消訂閱。
總結(jié)
以上是生活随笔為你收集整理的android订阅管理,RXJAVA取消订阅封装-kotlin-Android的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python元素定位input butt
- 下一篇: mysql8添加索引_MySQL8.0新