How to abort large file upload with OkHttp?

Viewed 1041

I am using OkHttp 3.1.2. I've created file upload similar to the original recipe which is found here: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java

I can't find example how to abort an upload of large file upon user request. I mean not how to get the user request but how to tell the OkHttp to stop sending data. So far the only solution that I can imagine is to use custom RequestBody, add an abort() method and override the writeTo() method like this:

public void abort() {
    aborted = true;
}

@Override
public void writeTo(BufferedSink sink) throws IOException {
    Source source = null;
    try {
        source = Okio.source(mFile);
        long transferred = 0;
        long read;

        while (!aborted && (read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
            transferred += read;
            sink.flush();
            mListener.transferredSoFar(transferred);

        }
    } finally {
        Util.closeQuietly(source);
    }
}

Is there any other way?

1 Answers
Related