Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit Type Argument Kotlin and RxJava

Tags:

kotlin

rx-java

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>())
  }
like image 937
Eugene Avatar asked Nov 29 '22 06:11

Eugene


2 Answers

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()
}
like image 94
Vladimir Mironov Avatar answered Dec 04 '22 01:12

Vladimir Mironov


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
//..
like image 27
Fentino Avatar answered Dec 04 '22 01:12

Fentino