Home > Software design >  Subscribe to an observable when it's already running
Subscribe to an observable when it's already running

Time:03-01

I want to subscribe to an observable when it's already running.

E.g. I create an observable to emit some upload percentage somewhere in the app, and start that upload. When users launch another app screen, I need to show a progress bar of what's happing. What's the best way to do this?

This is my current code

private Observable<UploadPercentage> uploadFile(File file) {
    ProgressRequestBody fileUploadBody = new ProgressRequestBody(file, "multipart/form-data");

    MultipartBody.Part multipartFileBody =
            MultipartBody.Part.createFormData(
                    "file",
                    file.getName(),
                    fileUploadBody);

    InterfaceUpload apiService = retrofit.create(InterfaceUpload.class);

    Response<Void> emptyResponse = Response.success(null);

    Observable<Response<Void>> apiRequestObservable = apiService.uploadFile(
                    multipartFileBody
            )
            // It starts by emitting an empty response to follow the
            // percentage even though the api still have not responded
            .startWith(Observable.just(emptyResponse));

    Observable<Integer> percentageUploadedObservable = fileUploadBody.getProgressSubject();

    return Observable.combineLatest(
            percentageUploadedObservable,
            apiRequestObservable,
            (percentage, apiResponse) ->
            new UploadPercentage(percentage, apiResponse, file));
}

CodePudding user response:

You need to convert your observables to hot observables .. you can read more about hot and cold observables here https://github.com/Froussios/Intro-To-RxJava/blob/master/Part 3 - Taming the sequence/6. Hot and Cold observables.md

  • Related