2016-04-12 70 views
3

這是在Kotlin中使用RxJava的composeThreadTransformer的唯一可能方式嗎?我只是不喜歡compose函數中的<MyType>部分。可以省略它嗎?顯式類型參數Kotlin和RxJava

override fun call(): Observable<MyType> { 
    return Observable.just(getData()) 
     .compose(threadTransformer.applySchedulers<MyType>()) 
    } 

回答

14

Observable.compose是Java中缺少擴展功能的解決方法。沒有必要在科特林使用Observable.compose,因爲它支持擴展功能開箱:基於弗拉基米爾·米羅諾夫的回答

// 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() 
} 
0

。將此延伸至您的需求:

//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 
//..