Yellow beginnings

A few days ago I wrote a request with Okhttp and the code suddenly turned yellow. It’s usually written like this, and even encapsulation takes four steps

withContext(Dispatchers.IO){
    val client = OkHttpClient.Builder().build()
    val request = Request.Builder().build()
    client.newCall(request).execute()
}
Copy the code

But it suddenly turned yellow

I’m sorry to interrupt you with an blocking method call. That’s an Inappropriate use of try and catch

Cause of yellow

Improper blocking method call

What does that mean? First, coroutines are apis that encapsulate a thread pool. One piece of coroutine code will run on one thread, and multiple pieces of coroutine code may run on the same thread, making full use of threads. Improper blocking method calls, that is, this piece of code, can have an effect on the coroutine, so that multiple coroutine tasks running on one thread become this task running on one thread. Incomplete utilization.

To explore the yellow

Okhttp click on it

  @Throws(IOException::class)
  fun execute(a): Response

  fun enqueue(responseCallback: Callback)
Copy the code

I threw an IOException.

Try and catch can’t clear yellow, so it must be more abnormal. Writes a method that modifies the exception thrown

@Throws(NullPointerException::class)
fun execute(a){}Copy the code

Only IOException does this.

It’s only four lines of code. It must have something to do with coroutines.

IOException is inherited by more than 60 classes.

When you see a SocketException, you realize that a Socket is also an I/O operation, so let’s say the Socket is connected, and then it blocks, and then if the Socket suddenly breaks, you try and catch and close the Socket. So that means that this HTTP is requesting, doing an IO, and suddenly it breaks, and you just close the request. Here’s another example:

withContext(Dispatchers.IO){
    / /...IO operations/ /...
}
Copy the code

You have a request in a coroutine, and the coroutine doesn’t know how long it’s going to take to do the IO, and if it’s doing the IO all the time, the coroutine might just put it on a separate thread and keep blocking. This doesn’t do the real work of the coroutine. So the compiler prompts a warning: this blocking is not appropriate

To solve yellow

Cause: Code that coroutines think might throw AN IO exception may block forever, putting the code on the thread for execution.

Coroutines are things that take time, but don’t want to waste resources. So we expect everything to be executed on coroutines.

Solution: Throw code into a cancelable coroutine to execute

val response = suspendCancellableCoroutine<Response> {
    client.newCall(request).execute()
}
Copy the code

Indicates that this code can be cancelled. Response is returned on success, and the coroutine is cancelled on failure. You can also use call.cancel() for asynchrony

about

For my Httplib, Okhttp is simply wrapped. OnceHttp encapsulates the Request simply. For the user, it focuses on input and output parameters: Response. Body Input parameters: key, value map or bean a Request: host, API, header, body

Use: Configure before use

ktHttpConfig(this) {
    host = "https://www.wanandroid.com/"
    // Public header arguments
    header["appVersion"] = "1.0.0"
    // Public body argument
    / / mapData [" appVersion "] = "1.0.0"
    // You can pass in a client
    //okHttpClient = OkHttpClient.Builder().build()
}
Copy the code

Just request OnceRequest(). The API, header, and body are free to change

OnceRequest adds two intercepting methods

// Modify the requested data before requesting it
open fun beforeRequest(map:MutableMap<String,String>) = mapData
// Modify the returned data after the request
open fun <T> afterRequest(bean:T) : T = bean
Copy the code

Before a request, modify the parameters, after the request, modify the returned data. (For example: request other servers, encryption and decryption methods are different)

There are also three ways to return data

requestBackLiveData(): LiveData<T> 
requestBackFlow(): Flow<T>
requestBackBean():T
Copy the code

More content, not very perfect, continue to update

If you find this article helpful, please give it a thumbs up.

If there is a mistake in the content, I will change it in time.