簡體   English   中英

如何在繼續循環之前等待回調完成?

[英]How to wait for callback to finish before continuing the loop?

我正在嘗試在 for 循環中將onResponse添加到restMedia中的restaurantMediaList 然而,當循環結束時, restaurantMediaList為 null。 我該如何解決這個問題,以便在繼續下一次迭代之前先等待onResponse完成?

public void getImages(List<Restaurant> restaurantList, OnImageReceivedCallback callback){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://example.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        WordpressAPICall wordpressAPICall = retrofit.create(WordpressAPICall.class);
        
        for(int i = 0; i < restaurantList.size(); i++){
            String featuredMediaURL = restaurantList.get(i).get_links().getFeaturedMedia().get(0).getHref();
            featuredMediaURL.substring(featuredMediaURL.indexOf("v2")+1);
            Call<RestaurantMedia> restMediaCall = wordpressAPICall.getImage(featuredMediaURL);

            restMediaCall.enqueue(new Callback<RestaurantMedia>() {
                @Override
                public void onResponse(Call<RestaurantMedia> call, Response<RestaurantMedia> response) {
                    RestaurantMedia restMedia = response.body();
                    restaurantMediaList.add(restMedia);
                    //callback.onRestaurantListReceived(restaurantModels, restMedia);
                }

                @Override
                public void onFailure(Call<RestaurantMedia> call, Throwable t) {
                    Log.d("Fail to get media", t.toString());
                }
            });
        }
        
        callback.onImageReceived(restaurantMediaList);
        
    }

請記住,有restaurantList.size()不同的線程(每個都會觸發一個網絡請求),您唯一的選擇是使用一些鎖。

如果有一個 API 一起獲取所有圖像,請使用它並使用我的第一個代碼等待結果。

我還建議使用超時,因為如果由於某種原因不會調用onResponseonFailure ,您的調用線程將永遠休眠。 根據需要調整超時。

等待每個線程分別完成非常耗時,所以我建議讓它們 go 異步並在所有線程完成后繼續。

我將向您展示這兩種選擇。

等待每一個單獨等待:

CountDownLatch countDownLatch = new CountDownLatch(1);
restMediaCall.enqueue(new Callback<RestaurantMedia>() {
    @Override
    public void onResponse(Call<RestaurantMedia> call, Response<RestaurantMedia> response) {
          // Do your thing
          countDownLatch.countDown();
     }

    @Override
    public void onFailure(Call<RestaurantMedia> call, Throwable t) {
          // Do your thing
        countDownLatch.countDown();
    }
});
countDownLatch.await(1L, TimeUnit.SECONDS); // join thread with timeout of second

一起等待所有線程:

public void getImages(List<Restaurant> restaurantList, OnImageReceivedCallback callback){
    // Do your thing
    CountDownLatch countDownLatch = new CountDownLatch(restaurantList.size());
    for(int i = 0; i < restaurantList.size(); i++){
        // Do your thing
        restMediaCall.enqueue(new Callback<RestaurantMedia>() {
            @Override
            public void onResponse(Call<RestaurantMedia> call, Response<RestaurantMedia> response) {
              // Do your thing
              countDownLatch.countDown();
             }

            @Override
            public void onFailure(Call<RestaurantMedia> call, Throwable t) {
                 // Do your thing
                 countDownLatch.countDown();
            }
        });
    }
    countDownLatch.await(1L *  restaurantList.size(), TimeUnit.SECONDS); // join thread with timeout of second for each item
}

暫無
暫無

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

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