Answer the question
In order to leave comments, you need to log in
How to get return in retrofit 2 in async request?
I want to receive a return in an asynchronous request, I understand that the response will come later and will call the method, but I need to contact it and get the answer right away or so that it would hold the completion of the
function to receive the response:
public void loadMyMuvi(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.0.105:8000")
.addConverterFactory(GsonConverterFactory.create())
.build();
final MyApiRequestInterface request = retrofit.create(MyApiRequestInterface.class);
Call<MyMuviResponse> call = request.getMyMuvi();
call.enqueue(new Callback<MyMuviResponse>() {
@Override
public void onResponse(Call<MyMuviResponse> call, Response<MyMuviResponse> response) {
MyMuviResponse myMuviResponse = response.body();
if (myMuviResponse.getStatus() == "true") {
data = new ArrayList<>(Arrays.asList(myMuviResponse.getMyMuvi()));
} else {
Log.d(TAG, "нет данных по запросу");
}
}
@Override
public void onFailure(Call<MyMuviResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
Answer the question
In order to leave comments, you need to log in
display a circle, etc. until there is an answer.
Answer a onfailure or onresponse
Why block anything at all? Bad practice.
You can stir up events (most likely), but why?
@Override
public Response load(Uri uri, int networkPolicy) throws IOException {
final AtomicReference<Object> notifier = new AtomicReference<>();
serverId = "https://" + Utils.API_SERVER_HTTP + "/download/" + serverId;
fileDownloader = new FileDownloader(serverId, outPath, true, new FileDownloader.IFileDownloaderListener() {
@Override
public void onProgress(int progress) {
}
@Override
public void onSuccess() {
synchronized (notifier) {
try {
notifier.set(new Response(decodeBitmap(outPath), false));
} catch (Exception ex) {
ex.printStackTrace();
notifier.set(new Exception());
} finally {
notifier.notify();
}
}
}
@Override
public void onError() {
synchronized (notifier) {
notifier.set(new Exception());
notifier.notify();
}
}
}, staticHandler);
fileDownloader.execute();
synchronized (notifier) {
try {
while (notifier.get() == null)
notifier.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (notifier.get() instanceof Exception)
{
throw new ResponseException("File cannot be downloaded", 0, 404);
}
return (Response) notifier.get();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question