Suppose I have a method with a listener (for example, I chose a request to VK Api, it was at hand):

private void getSubscribersInGroup() throws Exception { //Устанавливается пауза, чтобы код не выполнялся, пока //не будет получен ответ в слушатель isPause = true; //Создаю запрос (указываю что мне нужно получить) final VKRequest request = VKApi.groups().getMembers(VKParameters.from( VKApiConst.GROUP_ID, groupId, VKApiConst.COUNT, 0)); //Посылаю запрос и устанавливаю слушатель с методами request.executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { //Обрабатываю ответ и получаю его в ГЛОБАЛЬНУЮ переменную subscribersCount = getCountFromJSON(response.responseString); //Отключаю паузу, чтобы код продолжился isPause = false; } @Override public void onError(VKError e) { //По скольку это метод из API, я не могу выбрасывать Exception, //приходится прибегать к такому варианту isError = true; error = "error when requesting count: " + e.errorMessage; isPause = false; } @Override public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) { //Аналогично предыдущему методу isError = true; error = "onAttemptFailed when requesting count: " + "attemptNumber = " + attemptNumber + "totalAttempts = " + totalAttempts; isPause = false; } }); //Метод просто вызывает в бесконечном цикле "wait" на 100 миллисекунд, //с условием (isPause) waitResponseFromServer(); //Если была ошибка — кидаю исключение if (isError) throw new Exception(error); } 

I want to return the variable count through return , and not to use a global variable. Listener methods have access only to final method variables, so I cannot access them directly. Android Studio offered the option to make the variable count array - final int[] count = new int[1]; and then work with the first element of the array. As for me, this is a bit of an obvious move that I don’t like much. Are there other options to return the subscribersCount variable from the method so as not to use a global variable?

    1 answer 1

    You will not be able to return a variable through return, since the request is asynchronous. You can pass listener to this method.

     private void getSubscribersInGroup(final OnSubscriptionListener listener) 

    where OnSubscriptionListener:

     public interface OnSubscriptionListener { void onUpdateSubscribersCount(int subscribesCount); } 

    and call it inside onComplete (VKResponse response)

     request.executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { //Обрабатываю ответ и получаю его в ГЛОБАЛЬНУЮ переменную int subscribersCount = getCountFromJSON(response.responseString); if (listener != null) { listener.onUpdateSubscribersCount(subscribersCount); } //Отключаю паузу, чтобы код продолжился isPause = false; } 

    It is not clear for what purposes you need to return it through return

    • I gave the example with VK Api solely for the example, I am interested in return through return , because I often come across this. - user189127
    • 2
      It's not about the VK API example. If you want to return a value from the name, call it A, within which another method will be executed with a callback, call it B (i.e., run asynchronously), and if you want a value that returns the callback of method B to return in method A, then it is not possible. Impossible, because they are executed asynchronously, i.e. while you wait for the callback call for method B, the return method A will be called for a long time. - Yury Pashkov