这是我会做的以显示进度.
Observable downloadObservable = Observable.create(
sub -> {
InputStream input = null;
OutputStream output = null;
try {
Response response = http_client.newCall(request).execute();
if (response.isSuccessful()) {
input = response.body().byteStream();
long tlength= response.body().contentLength();
output = new FileOutputStream("/pathtofile");
byte data[] = new byte[1024];
sub.onNext("0%");
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
sub.onNext(String.valueOf(total*100/tlength) + "%");
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
} catch(IOException e){
sub.onError(e);
} finally {
if (input != null){
try {
input.close();
}catch(IOException ioe){}
}
if (out != null){
try{
output.close();
}catch (IOException e){}
}
}
sub.onCompleted();
}
);
并使用具有完整抽象方法的订阅者.
Subscriber mySubscriber = new Subscriber() {
@Override
public void onCompleted() {
// hide progress bar
}
@Override
public void onError(Throwable e) {
// hide progress bar
}
@Override
public void onNext(String percentProgress) {
// show percentage progress
}
};