我有IntentService,用于按顺序将照片文件上传到服务器。我有Gallery片段显示上传队列中的文件和已上传到服务器的文件。我使用api-call到服务器获取已上传文件的列表。将上传的本地文件只存储在DB中。
上传下一个文件后 - IntentService会将事件发送到Gallery片段。之后,我可以隐藏上传文件的进度轮,并从DB中删除有关该文件的记录。这部分工作得很好。
出于同步原因,我想阻止来自上传服务的所有事件(让他们等待),同时获取用于获取远程文件的api请求。
我担心的是 - 某些文件可以同时上传请求远程文件,我将丢失该事件。如何在api-request完成之前延迟从服务传递事件?
答案 0 :(得分:0)
在您的片段中,您可以执行此操作:
boolean isRequestingAPI = false;
.
.
.
//Requesting API on server
isRequestingAPI = true
synchronize(isRequestingAPI){
// do request API here
//You get callback from API
isRequestingAPI = false;
}
.
.
.
//Getting event from Service
private void onEventFromServceListener(){
if(isRequestingAPI){
//Put event/data in a queue and consume it when when you get callback from API
}
synchronize(isRequestingAPI){
//do whatever your want to do with event from service
}
}
使用synchronize(isRequestingAPI)
您的API调用和来自服务的事件将成为互斥事件。每个事件都会等待其他事件先完成。