RxKotlin 官网地址:https://github.com/ReactiveX/RxKotlin
RxAndroid 官网地址:https://github.com/ReactiveX/RxAndroid
RxKotlin是一个轻量级的库,它为RxJava添加了方便的扩展功能。您可以直接使用RxJava和Kotlin,但是Kotlin具有语言功能(例如扩展功能),可以进一步简化RxJava的使用。RxKotlin旨在保守地在一个集中式库中收集这些便利,并标准化将RxJava与Kotlin一起使用的约定。
import io.reactivex.rxjava3.kotlin.subscribeBy
import io.reactivex.rxjava3.kotlin.toObservable
fun main(args: Array) {
val list = listOf("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
list.toObservable() // extension function for Iterables
.filter { it.length >= 5 }
.subscribeBy( // named arguments for lambda Subscribers
onNext = { println(it) },
onError = { it.printStackTrace() },
onComplete = { println("Done!") }
)
}
下面展示下实际案例中的应用
项目级别build.gradle
ext.rx_kotlin_version = "1.0.0"
ext.rx_android_version = "1.2.1"
base级别
api "io.reactivex:rxkotlin:$rx_kotlin_version"
api "io.reactivex:rxandroid:$rx_kotlin_version"
同步代码
新建包与文件
UserServiceImpl
package com.anguo.user.service.impl
import com.anguo.user.service.UserService
import rx.Observable
class UserServiceImpl : UserService {
override fun register(moible: String, verifyCode: String, pwd: String): Observable {
return Observable.just(true);
}
}
UserService
package com.anguo.user.service.impl
import com.anguo.user.service.UserService
import rx.Observable
class UserServiceImpl : UserService {
override fun register(moible: String, verifyCode: String, pwd: String): Observable {
return Observable.just(true);
}
}
之前博客注册的逻辑优化。。写好会报错。。因为execute 是我们自己扩展。。慢慢往下看就集成好了
package com.anguo.user.present
import com.anguo.baselibary.ext.execute
import com.anguo.baselibary.presenter.BasePresenter
import com.anguo.baselibary.rx.BaseSubscriber
import com.anguo.user.present.view.RegisterView
import com.anguo.user.service.impl.UserServiceImpl
class RegisterPersenter : BasePresenter() {
fun register(mobile: String, verifyCode: String,pwd: String) {
/*业务逻辑*/
val userService=UserServiceImpl()
userService.register(mobile,verifyCode,pwd)
.execute(object : BaseSubscriber(){
override fun onNext(t: Boolean) {
mView.onRegisterResult(t)
}
})
}
}
execute 是我们自己定义的扩展
package com.anguo.baselibary.ext
import com.anguo.baselibary.rx.BaseSubscriber
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
fun Observable.execute(subscriiber: BaseSubscriber) {
this.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(subscriiber)
}
BaseSubscriber是我们自己定义的基类 是为了避免接口每次都要回调三个接口,而我们实际常用只有一个next
重写后可以根据自己想要的方法去自己重写-
package com.anguo.baselibary.rx
import rx.Subscriber
open class BaseSubscriber : Subscriber() {
override fun onNext(t: T) {
}
override fun onCompleted() {
}
override fun onError(e: Throwable?) {
}
}