1
Good from what I understand the method call.enqueue(new Callback<Void>() {
initiates a thread to communicate with webservice. So I thought I’d slow down the method by putting one thread.sleep(2000)
to display my ProgressDialog
realized that by putting the sleep
did not interrupt the thead created by retrofit and yes the main Ui thread locking the ProgressDialog
.
Is there any way to put one Thread.sleep
within the method call.enqueue
to simulate a response delay of webserver?
package com.amazongas.paulo.crudbasicandroid.dao;
import android.util.Log;
import com.amazongas.paulo.crudbasicandroid.api.ApiCallback;
import com.amazongas.paulo.crudbasicandroid.api.DataService;
import com.amazongas.paulo.crudbasicandroid.model.Contato;
import com.google.gson.Gson;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ContatoDao {
public void salvar(Contato contato, final ApiCallback callback){
Gson gson = new Gson();
String json = gson.toJson(contato);
DataService dataService = DataService.retrofit.create(DataService.class);
Call<Contato> call = dataService.gravar(contato.getNome(),contato.getTelefone());
call.enqueue(new Callback<Contato>() {
@Override
public void onResponse(Call<Contato> call, Response<Contato> response) {
if(response.isSuccessful()){
//Simular retardo do server
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
callback.onResponse(response.body() != null);
//Boolean success = response.body().getSuccess();
int lastId = response.body().getCod();
Log.d("resultado","JSON: "+lastId);
}
}
@Override
public void onFailure(Call<Contato> call, Throwable t) {
call.cancel();
callback.onResponse(false);
Log.d("resultado","JSON: ERROR");
}
});
}
}
According to https://square.github.io/retrofit/,
On Android, callbacks will be executed on the main thread
, In other words, there is no way to simulate a waiting time for the callback of the Retrofit without locking the UI. You can mock the webserver and make the request take 2sec... They appear to have a mock API https://github.com/square/retrofit/tree/master/retrofit-mock.– Ruben O. Chiavone