Retrofit has been updated to version 2.6.0 with built-in support for Kotlin Coroutines, further simplifying the process of making web requests using Retrofit and Coroutines. In fact, throughout the history of programming languages, from assembly to C/C++, from Java and OC to Swift, Kotlin, and even Python, which is included in the textbook, there is a common feature. As cpus become more powerful, productivity seems to be a common goal for modern high-level programming languages. Kotlin is a good example. Java does require more code to do the same thing and do the same function, and Kotlin does make Android development more efficient. In particular, for asynchronous tasks, Kotlin provides coroutines that Java does not have. For an introduction to Kotlin Coroutines, read my three previous translations:
Using coroutines on Android: Getting The Background
Using coroutines on Android part 2: Getting started
Using coroutines on Android (3) : Real Work
Back to the topic, this article will focus on how coroutines are used in Retrofit version 2.6.0, but not on principle. I’m using my own WanAndroid app as an example of a Retrofit version 2.4.0 in the source code. This wanAndroid is based on Kotlin + coroutine + LiveData + MVVM implementation, concrete architecture visible my article is really sweet! Kotlin+MVVM+LiveData+ coroutine build Wanandroid! Personally, I think the code is relatively clear, and it is suitable for Kotlin’s entry project.
Use of older versions of Retrofit
Before I show you how to use Retrofit 2.6.0, let’s take a look at how older versions of Retrofit work based on Kotlin Coroutines, using the login interface as an example.
First define the WanService interface as follows:
@POST("/user/login")
fun login(@Field("username") userName: String.@Field("password") passWord: String): Deferred<WanResponse<User>>
Copy the code
Note that the return value used here is a Deferred
object, which means that the return value must be obtained with an await. How do you get Retrofit to return Deferred
directly? Also using JakeWharton’s open source library:
implementation 'com. Jakewharton. Retrofit: retrofit2 - kotlin coroutines -- adapter: 0.9.2'
Copy the code
Add this adapter when building the Client:
. .addCallAdapterFactory(CoroutineCallAdapterFactory.invoke()) ...Copy the code
Then provide a suspend method for the LoginRepository:
suspend fun login(userName: String, passWord: String): WanResponse<User> {
return apiCall { WanRetrofitClient.service.login(userName, passWord).await() }
}
Copy the code
We use await here to get the return value of Deferred
.
The final call in LoginViewModel looks like this:
fun login(userName: String, passWord: String) {
launch {
val response = withContext(Dispatchers.IO) { repository.login(userName, passWord) }
executeResponse(response, { mLoginUser.value = response.data }, { errMsg.value = response.errorMsg })
}
}
Copy the code
The launch() method is packaged in a simple way, so you can check out the source code if you’re interested.
That’s the basic way to use coroutines in Retrofit 2.4.0, but the code is pretty neat. And Retrofit 2.6.0 makes it even easier! Let’s take a look!
Use of coroutines in Retrofit 2.6.0
Talking is cheap, show me the code ! Still the login interface above, Retrofit 2.6.0.
First, modify the Retrofit dependency.
implementation 'com. Squareup. Retrofit2: retrofit: server'
Copy the code
Second, modify the definition of the interface in WanService.
@POST("/user/login")
suspend fun login(@Field("username") userName: String.@Field("password") passWord: String): WanResponse<User>
Copy the code
See the difference? First, instead of returning the Deferred
object, we simply return the WanResponse object we need. Second, you use suspend to modify the method, marking it as a suspended function.
Third, modify the method definitions in the LoginRepository.
suspend fun login(userName: String, passWord: String): WanResponse<User> {
return apiCall { WanRetrofitClient.service.login(userName, passWord) }
}
Copy the code
In contrast to previous versions, there is no need to call the await method. It’s not that we don’t call it anymore, but Retrofit helps us call it automatically.
Finally, don’t forget to remove the kotlin-Coroutines-Adapter we added, because we no longer need to manually return Deferred
objects and call await objects manually.
.//.addCallAdapterFactory(CoroutineCallAdapterFactory.invoke()).Copy the code
At this point, the Retrofit version 2.6.0 transformation is complete. My Wanandroid project has completed all the changes, see commit for details.
conclusion
As Kotlin becomes the language of choice for Android development, more and more new features will be prioritized on Kotlin. Coroutine as a Kotlin asynchronous weapon, it is worth learning. If you haven’t already, start with my Wanandroid!
The article first published wechat public number: Bingxin said, focus on Java, Android original knowledge sharing, LeetCode problem solution.
For more related knowledge, scan the code to follow me!