【发布时间】:2016-01-23 02:39:52
【问题描述】:
所以我有一个轨道 ID 列表,对于每个轨道 ID,我需要执行网络请求以获取轨道详细信息,我使用 for 循环来启动所有请求,并使用锁存器等待所有请求完成。完成后,回调将与已填充的曲目列表一起发送。
我想知道是否有更好的方法来做到这一点,也许使用 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;
}
【问题讨论】:
标签: java android multithreading retrofit rx-java