Skip to content

Instantly share code, notes, and snippets.

@Evin1-
Last active August 5, 2020 02:26
Show Gist options
  • Save Evin1-/fc217b6118fe5cc298aa4743f1f101aa to your computer and use it in GitHub Desktop.
Save Evin1-/fc217b6118fe5cc298aa4743f1f101aa to your computer and use it in GitHub Desktop.
Loop Cupcakes. Retrofit with Coroutines
<uses-permission android:name="android.permission.INTERNET" />
// build.gradle (:app)
android {
//..
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
//.. https://square.github.io/retrofit/
//.. https://developer.android.com/kotlin/ktx
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* Creates an instance of the UserService using a simple Retrofit builder using Moshi
* as a JSON converter, this will append the endpoints set on the UserService interface
* (for example '/api', '/api?results=2') with the base URL set here, resulting on the
* full URL that will be called: 'https://randomuser.me/api' */
val service = Retrofit.Builder()
.baseUrl("https://randomuser.me/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(UserService::class.java)
/* Uses the lifecycle scope to trigger the coroutine. It's important to call this
* using a scope to follow the structured concurrency principle.
* https://medium.com/@elizarov/structured-concurrency-722d765aa952
* https://developer.android.com/topic/libraries/architecture/coroutines */
lifecycleScope.launch {
val users = service.getUsers()
/* This will print the result of the network call to the Logcat. This runs on the
* main thread */
Log.d("TAG_", users)
}
}
}
/* Kotlin data/model classes that map the JSON response, we could also add Moshi
* annotations to help the compiler with the mappings on a production app */
data class UserResponse(val results: List<User>)
data class User(val email: String, val phone: String)
/* Retrofit service that maps the different endpoints on the API, you'd create one
* method per endpoint, and use the @Path, @Query and other annotations to customize
* these at runtime */
interface UserService {
@GET("/api")
suspend fun getUsers(): UserResponse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment