Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

android - How can I implement REAL syncronized call with retrofit2?

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?


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

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...