How to use Retrofit in Android

Issue #366

Code uses Retrofit 2.6.0 which has Coroutine support

app/build.gradle

1
2
3
4
5
6
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

1
2
3
4
5
6
import retrofit2.http.GET

interface Api {
@GET("api/articles")
suspend fun getArticles(): List<Article>
}

Repo.kt

1
2
3
4
5
6
7
8
9
10
11
12
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

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
import com.squareup.moshi.Json

data class Article(
@field:Json(name="type_of") val typeOf: String,
@field:Json(name="title") val title: String
)

Comments