如何使用Bifunction Single和Observable实现Observable zip?

时间:2018-01-29 20:32:54

标签: android observable

如何使用Bifunction正确实现Observable.zip?

一个返回一个,一个返回一个Observable,不确定是否可能。

感谢您的评论,这是我的更新。我不确定在下面的BiFunction放什么

    Observable.zip(
            mCurrentUserViewModel.getUserProfile(getUserProfileRequest).toObservable(),
            mTopicsByCurrentUserViewModel.getTopicsByCreator(getTopicsByCreatorRequest)),
            new BiFunction<Single<GetUserProfileResponseBody>, Observable<Response<GetTopicsByCreatorResponseBody>>, **what do i put here**>()
    );

2 个答案:

答案 0 :(得分:0)

示例zip函数:

    private Observable<String> stringObservable() {
        return Observable.just("D");
    }

    private Observable<Integer> integerObservable() {
        return Observable.just(1);
    }

    private Observable<String> resultObservable(){
        return Observable.zip(stringObservable(), integerObservable(), new BiFunction<String, Integer, String>() {
            @Override public String apply(String s, Integer integer) throws Exception {
                return s + integer;
            }
        });
    }

    private Observable<String> resultObservableLambda(){
        return Observable.zip(stringObservable(), integerObservable(), (s, i) -> s + i);
    }

您缺少的第3项是您的退货类型。那么您想要返回的聚合类型是什么 - 在此示例中为String,因此返回一个新的Observable Observable<String>

答案 1 :(得分:0)

您有两种选择。

toSingle()将发出单个项的Observable 转换为发出此项目的Single

toObservable将Single转换为Observable。

例如:使用toObservable()

1 - 创建您的可观察量

private Observable<String> getObservable() {
    return Observable.just("observable");
}

private Single<String> singleObservable() {
    return Single.just("single");
}

private Observable<String> mergedObservable() {
    return Observable.zip(getObservable(), singleObservable().toObservable(), new BiFunction<String, String, String>() { //the result of merging is also String
        @Override
        public String apply(String s, String s2) {
            return s + s2;  //or if you are using different objects create a model AandB. where A and B are the result of a seperate observers.
        }
    });
}

2合并

           mergedObservable().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new Observer<String>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(String s) {
                    Log.d(tag,s);
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

<强>输出
observablesingle