所以我有一個Track Id的列表,我需要執行一個網絡請求來獲取軌道詳細信息,我使用for循環來啓動所有請求和鎖等待所有請求完成。完成後,回調將與已填充的曲目列表一起發送。避免使用CountDownLatch在發送回調之前等待多個線程
我想知道是否有更好的方法來做到這一點,也許與RxJava?
我在Android中使用Retrofit 2.0。
public IBaseRequest batchTracksById(final TrackIdList trackIdListPayload, final IRequestListener<TracksList> listener) {
final TracksList tracks = new TracksList();
final Track[] trackArray = newrack[trackIdListPayload.getTrackIds().length];
tracks.setTrack(trackArray);
final CountDownLatch latch = new CountDownLatch(trackArray.length);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
latch.await();
handler.post(new Runnable() {
@Override
public void run() {
listener.onRequestUpdate(null, tracks, null, true);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
for (String id : trackIdListPayload.getTrackIds()) {
getTrackById(id, new IRequestListener<Track>() {
@Override
public void onRequestFailure(IBaseRequest request, Exception exception) {
latch.countDown();
}
@Override
public void onRequestUpdate(IBaseRequest request, Track track, RequestState state, boolean requestComplete) {
//iterate through the tracks and update the ones in the thing
int i = 0;
for (String s : trackIdListPayload.getTrackIds()) {
if (s.equals(track.getTrackId())) {
trackArray[i] = track;
// don't break here, as we may have a case where we have multiple instances of the same trackId (although
// at the moment a request will be made for each anyway...
}
i++;
}
latch.countDown();
}
});
}
return null;
}