简体   繁体   中英

Keep stream alive even after onComplete()

There are two issues which I am currently facing.

1) As soon as the line RetrofitProvider.getInstance().getCurrentWeather(.....) is called the network call is being done. How can it be deferred till the observer is connected to it.

2) Once weatherInfoPublisher.onComplete() is called, the next time I call onComplete on this object the new observer's onNext is not getting called.

public Observable<LinkedList<WeatherInfo>> getWeatherData(final String payload, final TempUnit tempUnit) {

        PublishSubject weatherInfoPublisher = PublishSubject.create();

        RetrofitProvider.getInstance().getCurrentWeather(payload + ",us", translateTempUnit(tempUnit))
            .flatMap(new Function<String, ObservableSource<String>>() {
                @Override
                public ObservableSource<String> apply(String todayResponse) throws Exception {

                    Log.d(TAG, "Received today weather: " + todayResponse);

                    parseTodayData(todayResponse, weatherDataList);
                    return RetrofitProvider.getInstance().getForecastWeather(
                            payload + ",us", translateTempUnit(tempUnit), FORECAST_DAYS);
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableObserver<String>() {
                @Override
                public void onNext(String futureResponse) {

                    Log.d(TAG, "Received future weather: " + futureResponse);
                    parseFutureData(futureResponse, weatherDataList);

                    weatherInfoPublisher.onNext(weatherDataList);
                    weatherInfoPublisher.onComplete();
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "The error is, " + e.getMessage());
                }

                @Override
                public void onComplete() {

                }
            });

        return weatherInfoPublisher;
    }

This is a singleton class and the entire implementation has been provided in here in Github Link .

How can it be deferred till the observer is connected to it.

Do not subscribe to that observable in this method. Instead return that observable to the client. As soon as the observable is subscribed - a request would be performed.

the next time I call onComplete on this object the new observer's onNext is not getting called.

See reactive stream specs : if a stream completes - it can never be continued, that's a terminal event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM