M
M
miklce2016-07-01 03:47:53
Java
miklce, 2016-07-01 03:47:53

Passing a callback to a method as a parameter, normal practice or a crutch?

I implemented a class to work with my rest-like api using OkHTTP,
for example, the GetSomething() method

public class GetSomething {
  public void get(Callback callback,int limit, int offset) {
  OkHttpClient client = new OkHttpClient();
  // Готовим запрос, и отправляем как положено, асинхронно..
  // Ну а callback пихаем из параметра
  Request request = new Request.Builder().url(url).build();
  client.newCall(request).enqueue(callback);

And in the fragment, respectively, I do this:
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import ru.domain.user.app.api.getSomething;
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getSomething something = new getSomething();
  Callback callback = new Callback() {
   @Override
   public void onFailure(Call call, IOException e) { e.printStackTrace(); }
   @Override
   public void onResponse(Call call, Response response) throws IOException {
     try {
      String jsonData = response.body().string();
      JSONObject Jobject = new JSONObject(jsonData);
      Log.d("getSomething Resp",  Jobject.toString());
     } catch (JSONException e) {}
}

Everything is working. and I have a feeling that I started making crutches at the very beginning of the project...
Is that how they do it or is it just a crutch? How it is more correct to implement?
I just recently got into Java, wrote myself beautifully procedurally in puff ..
I don’t want to learn how to write crookedly))
582675.jpg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Gapchenko, 2016-07-01
@miklce

There is absolutely nothing wrong with your code. Requests in OkHttp are executed in a background thread (not in the main one, in which all the components of the Android application work, but in the background thread), so you need to somehow pass your reaction to the successful / erroneous execution of the request to OkHttp. Callbacks and b were added to OkHttp as a way to add this kind of response to data received on a background thread.

D
Dmitry Alexandrov, 2016-07-01
@jamakasi666

And what exactly do you want to get or do with callback? Pass a reference to some object and perform some logic, or just return the response based on the passed data?
Or transfer some magical method that the one who received it will use?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question