Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cancel if download not started in particular time. #693

Open
PratikLahagora opened this issue Sep 27, 2024 · 1 comment
Open

Cancel if download not started in particular time. #693

PratikLahagora opened this issue Sep 27, 2024 · 1 comment

Comments

@PratikLahagora
Copy link

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
        )
    }
@tonyofrancis
Copy link
Owner

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);
            }
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants