上篇中我们介绍了基于MVP的Retrofit2+RXjava封装,还没有看的
上篇中我们介绍了基于MVP的Retrofit2+RXjava封装,这一篇我们来说说文件下载的实现。
首先,我们先在ApiServer定义好调用的接口@GET
Observable downloadFile(@Url String fileUrl);
接着定义一个接口,下载成功后用来回调public interface FileView extends BaseView { void onSuccess(File file);
}
接着是Observer,建议与处理普通接口的Observer区分处理public abstract class FileObsever extends BaseObserver { private String path; public FileObsever(BaseView view, String path) { super(view); this.path = path;
} @Override
protected void onStart() {
} @Override
public void onComplete() {
} @Override
public void onSuccess(ResponseBody o) {
} @Override
public void onError(String msg) {
} @Override
public void onNext(ResponseBody o) {
File file = FileUtil.saveFile(path, o); if (file != null && file.exists()) {
onSuccess(file);
} else {
onErrorMsg("file is null or file not exists");
}
} @Override
public void onError(Throwable e) {
onErrorMsg(e.toString());
} public abstract void onSuccess(File file); public abstract void onErrorMsg(String msg);
}
FileUtil 注:如果需要写入文件的进度,可以在将这段方法放在onNext中,在FileObsever这个类写个方法,然后回调。public static File saveFile(String filePath, ResponseBody body) {
InputStream inputStream = null;
OutputStream outputStream = null;
File file = null; try { if (filePath == null) { return null;
}
file = new File(filePath); if (file == null || !file.exists()) {
file.createNewFile();
} long fileSize = body.contentLength(); long fileSizeDownloaded = 0; byte[] fileReader &#