java - 在回调 rxjava 中返回 Observable

标签 java android rx-java reactive-programming

我正在使用 google awareness api 搞乱一些东西,现在我对 RxJava 的理解限制了我。

我最终想达到的目的: 我想从 Api 获取 Weather 和 Location,并将它们合并到一个对象中,我可以将该对象传递给我的 View 以进行更新。

但是,我不确定如何从此处的 api 回调实现 Observable 的返回,因为它具有 void 返回类型,以及如何实现 api.getWeather 和 api.getLocation 的天气和位置对象的合并

public void requestUserCurrentInfo() {
    Subscription userInfo = getWeatherLocation().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(userinfo ->
                    Log.d(TAG,userinfo.something()));
}

public Observable<UserInfo> getWeatherLocation () {
    try {
        Awareness.SnapshotApi.getWeather(client)
                .setResultCallback(weather -> {
                    if (!weather.getStatus().isSuccess()) {
                        Log.d(TAG, "Could not get weather");
                        return;
                    }
                    //How do I do here?
                    return weather.getWeather();
                });


        Awareness.SnapshotApi.getLocation(mGoogleApiClient)
            .setResultCallback(retrievedLocation -> {
                if(!retrievedLocation.getStatus().isSuccess()) return;
                Log.d("FRAG", retrievedLocation.getLocation().getLatitude() + "");
            });


    } catch (SecurityException exception) {
        throw new SecurityException("No permission " + exception);

    }

}

对于我项目中的其他东西,我按照存储库模式通过 REST api 获取一些东西,然后我可以这样获取它,因为每个步骤都会返回一个 Observable< SmhiResponse >

getWeatherSubscription = getWeatherUsecase.execute().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe(
                    smhiResponseModel -> {Log.d(TAG,"Retrieved weather"); locationView.hideLoading();},
                    err -> {Log.d(TAG,"Error fetching weather"); locationView.hideLoading();}
            );

最佳答案

您不会从回调中返回一个可观察对象,而是将您的回调包装到可观察对象中以使其可组合(未经测试):

    Observable<WeatherResult> weatherObservable = Observable.create(subscriber -> {
        Awareness.SnapshotApi.getWeather(client)
                .setResultCallback(weather -> {
                    if (!weather.getStatus().isSuccess()) {
                        subscriber.onError(new Exception("Could not get weather."));
                        Log.d(TAG, "Could not get weather");
                    } else {
                        //How do I do here?

                        subscriber.onNext(weather);
                        subscriber.onCompleted();
                    }
                });
    });

    Observable<LocationResult> locationObservable = Observable.create(subscriber -> {
        Awareness.SnapshotApi.getLocation(mGoogleApiClient)
                .setResultCallback(retrievedLocation -> {
                    if(!retrievedLocation.getStatus().isSuccess()) {
                        subscriber.onError(new Exception("Could not get location."));
                    } else {
                        Log.d("FRAG", retrievedLocation.getLocation().getLatitude() + "");
                        subscriber.onNext(retrievedLocation);
                        subscriber.onCompleted();
                    }
                });
    });

现在通过 .combineLatest().zip() 组合它们:

    Observable<CombinedResult> combinedResults = Observable.zip(weatherObservable, locationObservable,
            (weather, location) -> {
                /* somehow combine weather and location then return as type "CombinedResult" */
            });

不要忘记订阅,否则它们都不会被执行:

    combinedResults.subscribe(combinedResult -> {/*do something with that stuff...*/});

关于java - 在回调 rxjava 中返回 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38119110/

相关文章:

java - Android Retrofit 从服务器下载/读取文本文件

java - 有了 Sping 的缓存支持(对于 ehcache),我们还需要 Hibernate 二级缓存吗?

java - 如何初始化一个二维数组?

java - 实现接口(interface)并聚契约(Contract)一接口(interface)的多个实现的抽象类。有它的模式(名称)吗?

java - 为网络浏览器开发用户定义的插件

android - 在没有 xml 的情况下以编程方式创建 Listview : not showing any cell

android - 是否可以像这样从字符串中剪切文本?

android - project_create.sh:第4行:android:找不到命令(cygwin&android&jni)

android - 将 Firebase 任务<Void> 包装到 RxJava CompletableEmitter 中?

java - RxJava : Chaining Observables w/Builder object