簡體   English   中英

如何使代碼等待所有請求完成 Android okhttp

[英]How to make the code wait for all of the requests to finish Android okhttp


        for(String number : numbers) {
            RequestBody formBody = null;

           ...


            client.newCall(request).enqueue(new Callback() {
               ....

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                   //blahblah
                }
            });

        }



here's the code that needs to wait for all of the responses above to arrive
        Intent myIntent = new Intent(context, PaidActivity.class);
        //blahblah
        context.startActivity(myIntent);
        context.finish();

    }

如何讓這個 Intent 等待上面的回調完成? 如何在收到服務器的所有響應后才停止和繼續?

只需將您的這些代碼放入 onResponse() 方法中,即可解決您的問題。 哦,別忘了檢查和包裝if(response.isSuccessful())

  if(response.isSuccessful()) {
    Intent myIntent = new Intent(context, PaidActivity.class);
    //blahblah
    context.startActivity(myIntent);
    context.finish();
  }

希望能幫助到你

您將需要某種計數器來跟蹤您的所有請求並在它們全部完成時執行一些代碼。 一個快速而骯臟的解決方案看起來像這樣:

AtomicInteger counter = new AtomicInteger(numbers.length);
for (String number : numbers) {
    RequestBody formBody = null;
    // ...
    client.newCall(request).enqueue(new Callback() {
        // ...

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            int currentCount = counter.decrementAndGet();
            if (currentCount <= 0) {
                // You might need to call this on the UI thread.
                Intent myIntent = new Intent(context, PaidActivity.class);
                context.startActivity(myIntent);
                context.finish();
            }
        }
    });
}

我會推薦使用例如更具反應性的方法。 RxJava而不是匿名回調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM