Issue #366
Code uses Retrofit 2.6.0 which has Coroutine support
app/build.gradle
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha01"
implementation "com.squareup.moshi:moshi:$Version.moshi"
implementation "com.squareup.retrofit2:retrofit:$Version.retrofit"
implementation "com.squareup.retrofit2:converter-moshi:$Version.retrofit"
Api.kt
import retrofit2.http.GET
interface Api {
@GET("api/articles")
suspend fun getArticles(): List<Article>
}
Repo.kt
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
class Repo {
fun get(): Api {
return Retrofit.Builder()
.baseUrl("https://dev.to")
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(Api::class.java)
}
}
ViewModel.kt
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import kotlinx.coroutines.Dispatchers
class ViewModel(val repo: Repo): ViewModel() {
val articles = liveData(Dispatchers.Main) {
emit(repo.get().getArticles().toCollection(ArrayList()))
}
}
Article.kt
import com.squareup.moshi.Json
data class Article(
@field:Json(name="type_of") val typeOf: String,
@field:Json(name="title") val title: String
)