Today's Android projects generally use the combination of Retrofit+RxJava to implement network interface requests and data presentation. This feature is also easily implemented through the Kotlin language's coroutine function.
In comparison, RxJava is too powerful, and if it is only used to encapsulate network requests, some feel like killing a knife. Using Kotlin's coroutines to achieve this requirement code is more streamlined and the logic is clearer.
The following is a complete example. Use Retrofit in conjunction with Kotlin coroutines to implement network requests.
Click the button in the Activity to request the openAPI of the V2ex website. After the success, the result field is displayed in the interface.
The code in the Activity is as follows:
class MainActivity : AppCompatActivity() {
var loadDataJob: Job? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
test_button.setOnClickListener {
showResult("")
loadDataJob?.cancel() // cancel the previous load task
loadDataJob = loadData("Livid") // “http://www.v2ex.com/api/members/show.json?username=Livid”
}
}
override fun onDestroy() {
super.onDestroy()
loadDataJob?.cancel() / / Cancel the load task
}
private fun showResult(resStr: String) {
test_result.text = resStr
}
private fun loadData(username: String): Job {
return excuteRequest<UserInfo>(
// request to call
request = {
userApiManager.getUserInfo(username)
},
// successful callback
onSuccess = {
showResult(it.bio)
},
// failure callback
onFail = {
it.printStackTrace()
})
}
}
inloadDataIn the function, throughexceteRequestThe method returns the Job object,exceteRequestThe network request, the logical operation of success and failure, are specified by the lambda parameter.
UserApiManagerA simple wrapper around the Retrofit call is implemented in the class:
@Nullable
public UserInfo getUserInfo(String name) throws Exception {
// Create an instance of Retrofit and interface api when the class is initialized
/*
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.readTimeout(5000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true).build();
retrofitBuilder =
new Retrofit.Builder().baseUrl("http://www.v2ex.com")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient);
retrofit = retrofitBuilder.build();
mApiService = retrofit.create(UserApiService.class);
*/
Response<UserInfo> result = mApiService.getUserInfo(name).execute(); // sync request
if (result.isSuccessful()) {
return result.body();
} else if (result.code() == 404) {
throw new Exception("404 Not Found");
}
return null;
}
Since we are going to implement asynchronous loading through the coroutine, we use it in the network request.excuteSynchronization method.
When the button is clicked, the previous load request is canceled, and then a new request is initiated; at the same time in the ActivityonDestroyIn the life cycle, the processing of canceling the load request is also performed.
excuteRequestNetwork request encapsulation is implemented using Kotlin coroutines:
fun <T> excuteRequest(request: suspend () -> T?, onSuccess: (T) -> Unit = {}, onFail: (Throwable) -> Unit = {}): Job {
val uiScope = CoroutineScope(Dispatchers.Main) // CoroutineScope of the UI main thread
return uiScope.launch {
try {
val res: T? = withContext(Dispatchers.IO) { request() } // Execute the network request in the IO thread. After success, return here to continue execution.
res?.let {
onSuccess(it)
}
} catch (e: CancellationException) {
Log.e("excuteRequest", "job cancelled")
} catch (e: Exception) {
Log.e("excuteRequest", "request caused exception")
onFail(e)
}
}
}
First start the coroutine in the UI thread, when executed towithContextRear,requestThe code block will switch to the IO thread executed by the scheduler, whileexcuteRequestThe function gives up control, so the UI thread does not block. whenrequestAfter the request is completed, the result is assigned tores Variable, UI thread returns againexcuteRequestIn the middle, continue to implement the subsequent part.
Multiple click on the interface button will print
job cancelled
Change a wrong url address and you will see
request caused exception
Through the coroutine, in the function executed sequentially, the effect of the callback function is realized, and the code logic is clearer. It is also more succinct than RxJava when called.
Transfer from, Based on original text trimming Some APIs initiate long-running operations (such as network IO, file IO, CPU or GPU intensive tasks, etc.) and require the caller to block until they are...
Foreword Use Retrofit and Rxjava and configure the network request port based on kotlin and use the Wikipedia search interface to get the number of search terms:https://en.wikipedia.org/w/api.php?acti...
I. Background Often see items with Retrofit + RxJava + RxAndroid frame, in order to understand the structure of the project. Now take a look, Retrofit: Retrofit Square is a framework developed by a ne...
Effect picture description: Use Kotlin new language to use Recyclerview in Android Studio 3.0 versionRealize the display of network data useAndroid StudioCreate a project, check here to support kotlin...
Code directly: OkhttpUtils: class OkhttpUtils { } Gradle introduction: // Introduce the JSON parsing framework implementation ‘com.alibaba:fastjson:1.1.72.android’ JsonUtils: class JsonUti...
Kotlin Coroutine series: 1. Introduction to Kotlin Coroutine 2. Kotlin Coroutine (coroutine) basics 3. Android use Kotlin Coroutine (Corporate) and Retrofit for network request and cancellation reques...
1. Process, thread, coroutine concept Process and thread The process is the smallest unit of resource allocation, and the thread is the smallest unit of program execution. A process has its own indepe...
Preface This articleNot discussThe principle and basic use of coroutine, Retrofit, MVVM, you can find good articles in other bloggers. This articleNoChoose the two-way binding method of DataBinding, b...
Foreword: There is a lot of introduction to the introduction of the Kotlin corporate corporation. The introduction of online requests is also a lot. This article does not explain various principles. I...
1. Call on the Activity 2. ViewMode writing 3. Request packaging API class 4.http interface Apiservice class...