Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Barros9/de1d26e3b7632f2672a96811465d6b70 to your computer and use it in GitHub Desktop.
Save Barros9/de1d26e3b7632f2672a96811465d6b70 to your computer and use it in GitHub Desktop.
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.Deferred
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
private const val BASE_URL = "PUT_HERE_URL"
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(
Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.baseUrl(BASE_URL)
.build()
interface ApiService {
@GET("PUT_HERE_GET_VALUE")
fun get():
Deferred<List<String>>
}
object Api {
val retrofitService: ApiService by lazy { retrofit.create(ApiService::class.java) }
}
@Barros9
Copy link
Author

Barros9 commented May 29, 2020

Retrofit Sample using Coroutine

Created a retrofit object pointing to the desired BASE_URL using a Moshi converter. An interface that expose the get() method, where @get annotation indicates the endpoint will be requested with the GET HTTP method, it returns a Coroutine Deferred List of String which can be fetched with await() if in a Coroutine scope.

Usage

CoroutineScope(Dispatchers.IO).launch {
    val getDeferred = Api.retrofitService.get()
    try {
        // Success
    } catch (e: Exception) {
        // Failure
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment