Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've seen a lot of posts and answers about syncronized call of Retrofit2.

It it's like:

// TODO: initial job

try{
    val response = ServiceGenerator.createService(this, MyService::class.java)!!
                .getItem(token, requestData)
                .execute()
    
    when{
        response.code >= 500->{
            // TODO: toast message
        }
        response.code >= 400->{
            // TODO: toast message
        }
        response.code >= 200->{
            // TODO: successful treatment
            val result = response.body()
            // ...
        }
    }
}catch(e: Exception){
}finally{
    // TODO: final job.
}

But if you implement it right into a method, you would get:

android.os.NetworkOnMainThreadException

Because it's not allowed. Otherwise, you need to do set the strict mode. However, this is not recommended.

Then, you need to implement the call in AsyncTask or Thread or Handler.

Then, it seems it goes back to the asyncronized call. Then, I am like... ???? Why not use enqueue() not execute(). But enqueue() is asyncronized call. And I don't want it!

So, I'd like to know REAL syncronized call with Retrofit2. How can I implement this?

I tried with @Syncronized Annotation to each method but I think it is a different problem because this only makes safe when many threads access to the method. However, In my case, I implement a method for a API call. For example, I have getUserInfo() and I implement like:

private fun getUserInfo(token, username, pw){
    val requestData = UserInfo(username, pw)

    ServiceGenerator.createService(this, MyService::class.java)!!
                .getItem(token, requestData)
                .enqueue(object: Callback<UserInfoResponse>{
                    override fun onResponse(call: Call<UserInfoResponse>, response: Response<UserInfoResponse>) {
                    }
                    
                    override fun onFailure(call: Call<UserInfoResponse>, t: Throwable) {
                    }
                })
}

How can I improve my usage of Retrofit2?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
369 views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...