1. 程式人生 > >Kotlin+RxJava+Retrofit2的簡單Demo

Kotlin+RxJava+Retrofit2的簡單Demo

所有的程式碼都寫在一個檔案內了

程式碼中所匯入的包,請務必注意不要導錯了,不然執行會導致報錯

程式碼如下:

import retrofit2.Call
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import rx.Observable import rx.schedulers.Schedulers /** * ==================================== * 作者:Jerry * 建立日期:2017/6/25 19:41 * 描述: * ==================================== */ /** * Retrofit 請求 */ interface IService { @GET("/repos/vmg/redcarpet/stargazers") fun getStarGazers(): Call<List<User>> @GET("/repos/vmg/redcarpet/issues"
) fun getIssues(@Query("state") state: String): Call<List<User2>> @GET("/repos/AndroidJerry8/SoulMate") fun getSoulMate(): Observable<Response<SoulMate>> } class Service { companion object { val service: IService by lazy(LazyThreadSafetyMode.NONE) { Retrofit.Builder
() .baseUrl("https://api.github.com") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(IService::class.java) } } } fun main(args: Array<String>) { val service = Service.service service.getStarGazers().execute().body().map(::println) service.getIssues("open").execute().body().map(::println) //Java 中 service.getSoulMate().subscribe({ result -> obtain(result) }, { t -> println(t.message) }) //Android 中 service.getSoulMate() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ result -> obtain(result) }, { t -> println(t.message) }) } fun obtain(response: Response<SoulMate>) { println("成功") if (response.isSuccessful) println(response.body()) else println(response.errorBody().string()) }

在下也是剛研究,有不足的地方,請多指教