The most elegant way to use Kotlin and Retrofit for network requests in Android projects, ditch Callback, ditch RxJava, embrace coroutines

Source code portal: Android-Kotlin-retrofit-wrap

There’s a lot of Retrofit+Rxjava on the web or using callbacks, but using coroutines is really easy


Android projects are now mostly developed using Kotlin, and kotlin’s strengths are obvious, including coroutines

Okhttp +Retrofit is commonly used for network interaction. In OkHttp4.0 +, Kotlin has been used as the maintenance language. Retrofit also supports the suspend modifier in version 2.6.0. This makes it especially convenient to use Kotlin Retrofit for network interaction in Android projects

This project is an example of a Kotlin coroutine working with Retrofit to implement a network request

Step0: Add support for Kotlin and its coroutines to the Android project

  • Build. Gradle:

    Buildscript {ext.kotlin_version = '1.3.50' ext.kotlin_coroutines = '1.3.2'... Dependencies {classpath 'com. Android. View the build: gradle: 3.5.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" ... }}Copy the code
  • Add support to build.gradle in app directory and add dependencies:

    apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines" implementation "Org. Jetbrains. Kotlinx: kotlinx coroutines - android: $kotlin_coroutines" implementation 'androidx. Core: the core - KTX: 1.1.0' Implementation 'androidx. Appcompat: appcompat: 1.1.0' implementation ' '2.6.2. Com. Squareup retrofit2: retrofit. Implementation "com. Squareup. Okhttp3: okhttp: 4.2.0" implementation "com. Squareup. Okhttp3: logging - interceptor: 4.2.0"... }Copy the code

Step1: see the simple encapsulation of Retrofit for detailsRetrofitWrap.kt

Funinit (baseUrl: String, debugEnable: Boolean = false) { instance.retrofit = Retrofit.Builder().apply { baseUrl(baseUrl) client(okhttpClient(debugEnable)) AddConverterFactory (StringConverterFactory. The create ())}. The build ()} / access API service * * * * / fun < T > service (service: Class < T >) : T { if (instance.retrofit ! = null) { return instance.retrofit!! .create(service)} else {throw IllegalStateException(" Call retrofitwrap.init () first ")}}Copy the code

There are just two external methods:

  • init: initialize, configure baseUrl and whether to print logs. Other parameters can be added based on the source code
  • service: Gets the service instance, passes in the interface class that defines the API, and then calls the corresponding method to complete the data request

Step2: define the network interaction method according to the business, for exampleAPI.kt

interface API {
    @GET("test.json")
    suspend fun info(): String
}
Copy the code

Use Example, for detailsTestActivity.kt

  • Complete example:

    class TestActivity : AppCompatActivity(), CoroutineScope by MainScope() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) RetrofitWrap.init("https://okfood.vip/", False) btn.setonClickListener {content.text = "Loading..." launch { val data = withContext(Dispatchers.IO) { RetrofitWrap.service(API::class.java).info() } content.text = if (TextUtils.isEmpty(data)) "error" else data } } } override fun onDestroy() { super.onDestroy() cancel() } }Copy the code
  • instructions

    • Initialize theRetrofitWrap.initIt needs to be placed before the first request to the network, either in the Application
    • Not recommendedGlobalScopeGo to thelaunchA coroutine task is provided in Android for easy lifecycle managementMainScopeCalled at page destructioncancel()Avoid Memory leaks

Spare a tangent

  • The content of this project is just a demonstration of the minimalist way of use. In specific projects, corresponding adjustments can be made according to the project architecture, such as the use of ViewModel and LiveData

  • The same applies to database operations, since both networks and databases are how Android data is stored