使用Jetpack、Kotlin实现的RxJava自动注销库,你值得拥有!
//support
implementation 'com.android.support:appcompat-v7:28.0.0' //27.0.0 等
//RxJava1
implementation 'io.reactivex:rxjava:1.3.8'
//Rxlife1
implementation 'com.dhh:rxLife1:version'
//support
implementation 'com.android.support:appcompat-v7:28.0.0' //27.0.0 等
//RxJava2
implementation 'io.reactivex.rxjava2:rxjava:2.2.3'
//Rxlife2
implementation 'com.dhh:rxLife2:version'
Observable.timer(10, TimeUnit.SECONDS)
// 标准使用模式 , 自动在 [Lifecycle.Event.ON_DESTROY] 注销
.compose(RxLife.with(lifecycleOwner).bindToLifecycle())
// 指定在 [Lifecycle.Event.ON_DESTROY] 注销
.compose(RxLife.with(lifecycleOwner).bindOnDestroy())
// 指定在某一生命周期注销,不常用
.compose(RxLife.with(lifecycleOwner).bindUntilEvent(Lifecycle.Event.ON_DESTROY))
.subscribe { Log.d("RxLife2-onCreate", it.toString()) }
class RxLife2Activity : AppCompatActivity(), LifecycleOwnerScope {
override fun getLifecycleOwner(): LifecycleOwner {
if (this is LifecycleOwner) return this
return super.getLifecycleOwner()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rxlife2)
Observable.timer(1, TimeUnit.SECONDS)
//直接绑定到 Activity 的 onDestroy
.bindOnDestroy()
.subscribe {
}
}
}
class ViewModelTest : ViewModel(), DisposeScope {
val userName = MutableLiveData<String>()
init {
loadData()
}
fun loadData() {
Observable.timer(5, TimeUnit.SECONDS)
.map { "dhh" }
.doOnSubscribe { Log.d("VVV", "doOnSubscribe") }
.doOnDispose { Log.d("VVV", "doOnDispose") }
.bindOnDestroy()
.subscribe { userName.value = it }
}
override fun onCleared() {
super.onCleared()
dispose()
}
}
interface CustomDisposeScope : DisposeScope {
// add custom extension methods
fun <T> Observable<T>.commit(onNext: (T) -> Unit): Disposable {
return bindOnDestroy().observeOn(AndroidSchedulers.mainThread()).subscribe(onNext, {})
}
}
open class BaseViewModel : ViewModel(), CustomDisposeScope {
override fun onCleared() {
dispose()
}
}
class ViewModelTest : BaseViewModel() {
val userName = MutableLiveData<String>()
init {
loadData()
}
fun loadData() {
Observable.timer(5, TimeUnit.SECONDS)
.map { "dhh" }
.doOnSubscribe { Log.d("VVV", "doOnSubscribe") }
.doOnDispose { Log.d("VVV", "doOnDispose") }
.commit { userName.value = it }
}
}
Copyright 2019 dhhAndroid
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.