본문 바로가기

안드로이드

rxjava 파일 다운로드

 


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();

            }
        };
    }

}