I want to upload a file to S3 and then delete it when upload succeeds. I am using TransferUtility as
for(final File p:photos){
String key = getKey(p.getName());
TransferObserver observer = getTransferUtility().upload(S3_BUCKET,key,p);
observer.setTransferListener(new TransferListener() {
@Override
public void onStateChanged(int id, TransferState state) {
if(TransferState.COMPLETED == state){
p.delete();
}
}
@Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
}
@Override
public void onError(int id, Exception ex) {
}
});
}
Since upload is asynchronous, the call to onStateChanged is bound to be out of phase with the for-loop. So how do I make sure the correct file is deleted each time?
Update
One approach that could work is if I could grab the correct observer from inside onStateChanged. Then I could do
@Override
public void onStateChanged(int id, TransferState state) {
if(TransferState.COMPLETED == state){
Observer obs = getParentObserver();//similar to a Fragment's getActivity() or getContext()
File file = new File(obs.getAbsoluteFilePath());
file.delete();
}
}
Notice that the following won't work as the ids will likely never match
@Override
public void onStateChanged(int id, TransferState state) {
if (TransferState.COMPLETED == state) {
if (observer.getId() == id) {
String filePath = observer.getAbsoluteFilePath();
File file = new File(observer.getAbsoluteFilePath());
}
}
}