Is this the only possible way of using RxJava's compose
with ThreadTransformer
in Kotlin? I just don't like the <MyType>
part in compose
function. Is it possible to omit it?
override fun call(): Observable<MyType> {
return Observable.just(getData())
.compose(threadTransformer.applySchedulers<MyType>())
}
Observable.compose
is a workaround for the lack of extension functions in Java. There is no need to use Observable.compose
in Kotlin because it supports extension functions out of the box:
// default schedulers
fun <T> Observable<T>.applySchedulers(): Observable<T> {
return subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread())
}
// custom transformer
fun <T> Observable<T>.applySchedulers(transformer: ThreadTransformer): Observable<T> {
return compose(transformer.applySchedulers<T>())
}
override fun call(): Observable<MyType> {
return Observable.just(getData()).applySchedulers()
}
Based on Vladimir Mironov's answer. Extend this to your needs:
//Observable
fun <T> Observable<T>.applyIoScheduler() = applyScheduler(Schedulers.io())
fun <T> Observable<T>.applyComputationScheduler() = applyScheduler(Schedulers.computation())
private fun <T> Observable<T>.applyScheduler(scheduler: Scheduler) =
subscribeOn(scheduler).observeOn(AndroidSchedulers.mainThread())
//Single
fun <T> Single<T>.applyIoScheduler() = applyScheduler(Schedulers.io())
fun <T> Single<T>.applyComputationScheduler() = applyScheduler(Schedulers.computation())
private fun <T> Single<T>.applyScheduler(scheduler: Scheduler) =
subscribeOn(scheduler).observeOn(AndroidSchedulers.mainThread())
//Completable
//..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With