我正在嘗試使用Retrofit和OkHttp向服務器發出請求。我有下一課「AutomaticRequest.java」,它有一個請求從服務器獲取視頻。如何等待回調有數據?
public class AutomaticRequest {
public void getVideos(final AutomaticCallback callback){
MediaproApiInterface service = ApiClient.getClient();
Call<List<AutomaticVideo>> call = service.getAllVideos();
call.enqueue(new Callback<List<AutomaticVideo>>() {
@Override
public void onResponse(Call<List<AutomaticVideo>> call, Response<List<AutomaticVideo>> response) {
List<AutomaticVideo> automaticVideoList = response.body();
callback.onSuccessGettingVideos(automaticVideoList);
}
@Override
public void onFailure(Call<List<AutomaticVideo>> call, Throwable t) {
callback.onError();
}
});
}
}
我創建了隔壁班「AutomaticCallback.java」檢索數據。
public interface AutomaticCallback {
void onSuccessGettingVideos(List<AutomaticVideo> automaticVideoList);
void onError();
}
我打電話從片段喜歡下方式請求:
public class AllVideosFragment extends Fragment {
...
AutomaticCallback callback;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_allvideos, container, false);
new AutomaticRequest().getVideos(callback);
return view;
}
...
}
我怎樣才能等到回調有數據更新UI?謝謝。
同步請求將自動等待響應,但它會阻止主線程直到那時。你應該做一個異步請求,並在收到響應後,更新UI – nandsito