retrofit
kotlin可以使用retrofit結合coroutines去實現取得api的方法,那因為我是使用mvvm架構,所以我會把rretrofit而外寫成一個object然後在viewmodel中實作
object GoRetrofit{
private val retrofit: Retrofit by lazy{
Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val api: API by lazy {
retrofit.create(API::class.java)
}
viewmodel
fun coroutine(){
myScope.launch(Dispatchers.Main){
// progressBar.visibility = View.VISIBLE
retrofit()
// progressBar.visibility = View.GONE
}
}
private suspend fun retrofit() = withContext(Dispatchers.IO){
val response = GoRetrofit.api.getAPI()
if (response.isSuccessful) {
Log.i("RETROFIT TEST", response.body().toString())
data.postValue(response.body() as ArrayList<Post>)
}
}
當然也需要一個interface來response資料
interface API {
@GET("/posts")
suspend fun getAPI(): Response<List<Post>>
}
這樣就可以簡單的使用retrofit了