今どきの Retrofit と LiveData で Coroutine

ありがとうございます。


👉 Retrofit 

ご存知の通り Retrofit2 では、サスペンドな関数も利用できるようになっております。

👉 SpaceX REST API で試す Retrofit の coroutine 対応 


// NewModel.kt
@GET("/feed/here/")
suspend fun getData(@Query("token") token : String) : Status


// NewRepository.kt
class Repository {
  var client = RetrofitService.createService(JsonApi::class.java)
  suspend fun getData(token : String) = client.getData(token)
}

ので、以下のようなこれまでのコードは、


// OldViewModel.kt
val data = MutableLiveData<Status>()

private fun loadData(token: String){
  viewModelScope.launch {
    val retrievedData = withContext(Dispatchers.IO) {
      repository.getData(token)
    }
    data.value = retrievedData
  }
}

シンプルに以下のように書けます。


// NewViewModel.kt
val data : LiveData<Status> = liveData(Dispatchers.IO) {
      val retrievedData = repository.getData(token)
      emit(retrievedData)
    }

ありがとうございます。

👉 Exploring new Coroutines and Lifecycle Architectural Components integration on Android 
👉 Using Retrofit 2 with Kotlin coroutines - ProAndroidDev