取消多个下载任务react-native-blob-util



我试图在数组中推送下载任务并在单击时取消它们,但似乎推送的任务在外部范围内不可用。

let downloadTasks: StatefulPromise<FetchBlobResponse>[] = [];

开始下载

const handleDownloadOfflineData = async () => {
try {
await Promise.all(
uniqueMediaFiles.map((media, i) => {
const task = ReactNativeBlobUtil.config({
path: `${cacheDir}/${INTERACTIVE_TOUR_DIR}/${oneInteractiveTourDetailsMobile.id}/media/${media.bucketPath}`,
})
.fetch('GET', `${BUCKET_PATH}${media.bucketPath}`)
.progress((received, total) => {
//..
console.log('Progress: ', received / total);
});
downloadTasks.push(task); //Push the task
console.log('PUSH TASK: ', downloadTasks.length);
return task;
}),
).then(async _responses => {
//..
});
} catch (err) {
//..
}
};

取消任务

const handleCancelDownload = async () => {
console.log('CANCEL TASKS: ', downloadTasks.length);
downloadTasks.forEach(task => {
task.cancel();
});
};

当我在下载开始后点击按钮取消任务时,我从控制台日志中得到这个

PUSH TASK:  1
PUSH TASK:  2
PUSH TASK:  3
PUSH TASK:  4
PUSH TASK:  5
PUSH TASK:  6
Progress:  1
Progress:  1
Progress:  1
Progress:  1
Progress:  1
Progress:  0.0023231438670363127
CANCEL TASKS:  0

如您所见,任务被推送到数组中,但是在取消下载函数中,数组仍然是空的,我无法取消它们。

我如何使它工作?

我设法通过将downloadTasks变量更改为ref:

来做到这一点
const downloadTasks = useRef<StatefulPromise<FetchBlobResponse>[]>([]);

const handleDownloadOfflineData = async () => {
try {
await Promise.all(
uniqueMediaFiles.map((media, i) => {
let lastReceived = 0;
const task = ReactNativeBlobUtil.config({
path: `${cacheDir}/${INTERACTIVE_TOUR_DIR}/${oneInteractiveTourDetailsMobile.id}/media/${media.bucketPath}`,
})
.fetch('GET', `${BUCKET_PATH}${media.bucketPath}`)
.progress((received, total) => {
setDownloadedProgress(prev => {
return prev + Number(received) - lastReceived;
});
lastReceived = Number(received);
});
downloadTasks.current = [...downloadTasks.current, task];
console.log('PUSH TASK: ', downloadTasks.length);
return task;
}),
).then(async _responses => {
setHasDownloadedContent(true);
setIsOfflineContentUpToDate(true);
setIsDownloading(false);
setDownloadedProgress(totalDownloadSize); //Fixes missing progress for last file
});
} catch (err) {
//..
}
};
const handleCancelDownload = async () => {
try {
downloadTasks.current.forEach(task => {
task.cancel();
});
downloadTasks.current = [];
setDownloadedProgress(0);
setHasDownloadedContent(false);
setIsOfflineContentUpToDate(undefined);
const path = `${ReactNativeBlobUtil.fs.dirs.CacheDir}/${INTERACTIVE_TOUR_DIR}/${data?.oneInteractiveTourDetailsMobile.id}_${contentLocale}`;
if (!(await ReactNativeBlobUtil.fs.exists(path))) {
return;
}
await ReactNativeBlobUtil.fs.unlink(path);
} catch (err) {
Toast.show({
text1: t('toast.error.deleteDownloadFailed'),
text2: t('toast.error.deleteDownloadFailed.tryOptions'),
type: 'error',
});
}
};

相关内容

最新更新