Not sure if I asked the question correctly, but the point is ...

There is an application where there are more than 30 different requests.

All requests are implemented in one separate class with a constructor, each as a separate method using okhttp.

According to the onFailure in onFailure or in onResponse result is processed in different ways:

For example:

  • Activity1 - > запрос -> onsuccess -> act1.finish();

In Activity1 - public static act1 = this;

  • Or Activity2 - > запрос -> onsuccess -> view1.visible=Gone ;

In Activity2 -> public static view1 = view;

Etc.....

Question: how to correctly and correctly implement this interaction scheme ...?

  • you can throw all requests into one class, and contact him using the scheme you need - Andrew Goroshko

1 answer 1

In the same way as you act with onResponse and onFailure, just create your own interface. If each request is a separate object, then create a field in it containing the interface implementation. Like that:

 //описываем интерфейс, общий для всех запросов. T - тип данных, которые вернет запрос public interface Callback<T>{ void onSuccess(T res); void onError(Exeption e); } //предположим, что у нас запрос возвращает строку public class Query{ //сохраняем колбэк в свойстве private Callback<String> callback = null public Query(Callback<Strong> callback){ this.callback = callback } @Override void onResponse(Call call, Response response){ //когда выполнили запрос - вызываем реакцию из коллбэка if(callback != null){ callback.onSuccess(responseToString(res)) } } @Override void onFailure(Call call, IOException e){ if(callback != null){ callback.onError(e) } } } //говорим активити реализовывать наш коллбек и передаем эту самую активити в запрос как коллбэк public class MyActivivty extends MyActivity implements Callback<String>{ @Override public void onCLick(v: View){ Query q = Query(this); q.exec() } @Override public void onSuccess(String res){ //обрабатываем ответ } @Override public void onError(Exeption e){ //обрабатывает ошибку } }