I'm downloading a pdf file with retrofit, the way that i'm downloading it is by blocks. I use the Content-Range
header to obtain a range of bytes, then i need to write these bytes on a file
the problem is the order to write them. I'm using the flatMap()
function to return an observable for each request that must be done to download the file.
.flatMap(new Func1<Integer, Observable<Response>>() {
@Override
public Observable<Response> call(Integer offset) {
int end;
if (offset + BLOCK_SIZE > (contentLength - 1))
end = (int) contentLength - 1 - offset;
else
end = offset + BLOCK_SIZE;
String range = getResources().getString(R.string.range_format, offset, end);
return ApiAdapter.getApiService().downloadPDFBlock(range);
}
})
The downloadPDFBlock
receive an strings that is needed by a header : Range: bytes=0-3999
. Then i use subscribe function to write the bytes downloaded
subscribe(new Subscriber<Response>() {
@Override
public void onCompleted() {
Log.i(LOG_TAG, file.getAbsolutePath());
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(Response response) {
writeInCache(response);
}
}
});
But the problem is that the writing process is made unordered. For example: if the Range: bytes=44959-53151
is downloaded first, these will be the bytes that will be written first in the file. I have read about BlockingObserver
but i don't know if that could be a solution.
I hope you could help me.