packagecom.example.jvmannotationsampleimportio.reactivex.Single//fileName:SingleExt.kt/** * shortcut method to change T instance into Single<T> instance */fun<T:Any>T.toSingle():Single<T>{returnSingle.just(this)}
接下来的代码,实现将任意类型的List转成Observable实例
12345678910
packagecom.example.jvmannotationsampleimportio.reactivex.Observable//fileName:ObservableExt.kt/** * shortcut method to convert List<T> instance to Observable<List<T>> instance */fun<T:Any>List<T>.toObservable():Observable<List<T>>{returnObservable.fromArray(this)}
针对上面的代码,我们使用时会是下面的样子
123
//the old waySingleExtKt.toSingle("Kotlin");ObservableExtKt.toObservable(Arrays.asList("Kotlinc","Developer","Friends"));
@file:JvmName("RxUtil")@file:JvmMultifileClasspackagecom.example.jvmannotationsampleimportio.reactivex.Single//fileName:SingleExt.kt/** * shortcut method to change T instance into Single<T> instance */fun<T:Any>T.toSingle():Single<T>{returnSingle.just(this)}
123456789101112
@file:JvmName("RxUtil")@file:JvmMultifileClasspackagecom.example.jvmannotationsampleimportio.reactivex.Observable//fileName:ObservableExt.kt/** * shortcut method to convert List<T> instance to Observable<List<T>> instance */fun<T:Any>List<T>.toObservable():Observable<List<T>>{returnObservable.fromArray(this)}
修改后,就可以在Java中完全使用RxUtil调用了。
123
//a much better way using @file:JvmMultifileClassRxUtil.toSingle("Kotlin");RxUtil.toObservable(Arrays.asList("Kotlinc","Developer","Friends"));