Fetch icon indicating copy to clipboard operation
Fetch copied to clipboard

Cancel if download not started in particular time.

Open PratikLahagora opened this issue 1 year ago • 1 comments

I want to implement a feature where, if a download doesn’t start within a specified time, it should be canceled, and an error should be thrown. After reviewing various suggestions, I found that it can be achieved using a custom HttpDownloader. I've implemented the code as shown below, but it still doesn’t trigger any listener or status change.

private fun initDownloader(context: Context) {
        val fetchConfiguration: FetchConfiguration =
            FetchConfiguration.Builder(context).setDownloadConcurrentLimit(1)
                .setHttpDownloader(getOkHttpDownloader())
                .build()
        fetchDownloader = Fetch.getInstance(fetchConfiguration)
        fetchDownloader?.addListener(fetchDownloaderListener)
    }

    private fun getOkHttpDownloader(): OkHttpDownloader {
        val okHttpClient: OkHttpClient = OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .connectTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .build()
        return OkHttpDownloader(
            okHttpClient,
            Downloader.FileDownloaderType.SEQUENTIAL
        )
    }

PratikLahagora avatar Sep 27 '24 10:09 PratikLahagora

Hi @PratikLahagora This is an interesting use case. Your code seems to be the correct solution. Once a connection times out it should throw an Exception that Fetch will catch and forward to your code. Were you able to logic the actual call and see if the exception was thrown. Here is an example of a customer downloader that will catch the exception and log it.

    static class MyDownloader extends OkHttpDownloader {
        public MyDownloader(@Nullable OkHttpClient okHttpClient, @NonNull FileDownloaderType fileDownloaderType) {
            super(okHttpClient, fileDownloaderType);
        }

        @Nullable
        @Override
        public Response execute(@NonNull ServerRequest request, @NonNull InterruptMonitor interruptMonitor) {
            try {
                return super.execute(request, interruptMonitor);
            } catch (Exception e) {
                Timber.e(e); //log response here
                throw new RuntimeException(e);
            }
        }
    }

tonyofrancis avatar Dec 03 '24 00:12 tonyofrancis