I have a problem with lambda expression; I used lambda expression in return type method but return isDownloaded.get()
execute before lambda expression . how I can wait for lambda finish?
public boolean isDowloaded(int id) {
AtomicReference<Boolean> isdownload = new AtomicReference<>(false);
AtomicReference<List<Download>> downloadList = new AtomicReference<>();
MyApplication.getInstance().getFetch().getDownloads(downloads -> {
downloadList.set(downloads);
for (int i = 0; i < downloadList.get().size(); i++) {
if (downloadList.get().get(i).getExtras().getString("id","").equals(String.valueOf(id)) ) {
PlayerConstants.SONG_NUM = i;
isdownload.set(true);
}
}
});
// always return false in this case
return isdownload.get();
}
The lambda is not the problem there.
The getDownloads()
call is asynchronous. So the isDowloaded()
method that invokes that should not return a boolean
since it doesn't know when the processing will be finished.
It should be a void
method. One of the main Fetch
api feature is downloading in the background.
So you have to implement a callback to perform a post processing.
2 possibilities :
FetchListener
. For example :
MyApplication.getInstance().getFetch().getDownloads(downloads -> {
downloadList.set(downloads);
for (int i = 0; i < downloadList.get().size(); i++) {
//...
}
// ... DO your post processing here
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.