1
\$\begingroup\$

What is the best practice to run continually api request, like every 1-10 seconds.

Currently I am doing this which is not a good practice I think, it probably causes some overhead:

    countDownTimer = new CountDownTimer(10000, 2000) {
        @Override
        public void onTick(long millisUntilFinished) {
            apiRequest();
        }
        @Override
        public void onFinish() {
            countDownTimer.start();
        }
    };

 void apiRequest() {

    call = service.getImg();
    call.enqueue(new retrofit2.Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            if (response.isSuccessful()) {
              // some code...
            } else {
              // some code ...
            }

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toasty.error(LiveBroadcastActivity.this, "Error.", Toast.LENGTH_SHORT, true).show();
        }
    });
}
\$\endgroup\$
  • \$\begingroup\$ Do you want it to run only when the app is active, or also when the app is inactive? I am afraid that the answer can also be: "It depends". What is your // some code...? Right now we are left to guess some of your intentions, which is possible to make this question get closed. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. You might want to see Why is hypothetical example code off-topic for CR? \$\endgroup\$ – Simon Forsberg Aug 2 '17 at 16:34
  • \$\begingroup\$ I want to run it when the app is active \$\endgroup\$ – utdev Aug 3 '17 at 7:41
  • \$\begingroup\$ You can use Thread instead of CountDownTimer and exit from the Thread when activity has finished \$\endgroup\$ – Sam Sep 8 '17 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.