AppApi.java
import retrofit2.http.Streaming;
import retrofit2.http.GET;
import okhttp3.ResponseBody;
public interface AppApi {
@Streaming
@GET
Observable<Response<ResponseBody>> downloadFile(@Url String fileUrl);
}
PDFViewerFragment.java
import java.io.File;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.Okio;
import retrofit2.Response;
public class PDFViewerFragment extends Fragment {
private void downLoadPDF(){
String fileUri = "다운받을 파일 경로";
AppApi appApi = RetrofitAdapter.getClient(getActivity()).create(AppApi.class);
appApi.downloadFile(fileUri).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).flatMap(processResponse())
.subscribe(handleResult());
}
public Function<Response<ResponseBody>, Observable<File>> processResponse(){
return responseBodyResponse -> saveToDiskRx(responseBodyResponse);
}
private Observable<File> saveToDiskRx(final Response<ResponseBody> response){
return Observable.create(new ObservableOnSubscribe<File>() {
@Override
public void subscribe(@NonNull ObservableEmitter<File> subscriber) throws Throwable {
String filename=fileUri.substring(fileUri.lastIndexOf("/")+1);
File filePath = new File(getActivity().getFilesDir()+"/pdf");
File outputFile = new File(filePath, filename);
BufferedSink bufferedSink = Okio.buffer(Okio.sink(outputFile));
bufferedSink.writeAll(response.body().source());
bufferedSink.close();
subscriber.onNext(outputFile);
subscriber.onComplete();
}
});
}
private Observer<File> handleResult() {
return new Observer<File>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull File file) {
// 파일 다운완료시 여기서 파일 콜백받음
}
@Override
public void onError(@NonNull Throwable e) {
e.printStackTrace();
}
@Override
public void onComplete() {
mActivity.progressOFF();
}
};
}
}
'안드로이드' 카테고리의 다른 글
이미지 공유시 Uri 얻기 (0) | 2023.12.14 |
---|---|
android 10 이상 스크린 캡쳐 후 파일저장(screen capture view java) (0) | 2023.11.16 |
코틀린 apply, run, let (0) | 2023.11.10 |
자바 특정일에 다음날 이전날 (0) | 2023.09.19 |
Glide 큰 사이즈 이미지 로딩 (0) | 2023.09.19 |