Observable.zip问题

时间:2018-01-11 09:17:39

标签: java android kotlin rx-java observable

我使用Retrofit和RxJava从Facebook下载两页的帖子。我想通过Observable.zip下载它们,但我得到onError : An operation is not implemented: not implemented

我的代码:

    var fb1 = dataManager.getPosts(ApplicationConstants.FACEBOOK_PAGE_1, ApplicationConstants.FACEBOOK_APP_TOKEN, "70")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())


    var fb2 = dataManager.getPosts(ApplicationConstants.FACEBOOK_PAGE_2, ApplicationConstants.FACEBOOK_APP_TOKEN, "70")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())

val observableZip : Observable<PostList> = Observable.zip(fb1,fb2, object: Function<PostList, PostList>, BiFunction<PostList, PostList, PostList> {
            override fun apply(t: PostList): PostList {
            }


            override fun apply(t1: PostList, t2: PostList): PostList {
            }

        })

        compositeDisposable.add(observableZip.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
                {result -> posts.addAll(result.data)},
                {t : Throwable? -> Log.d("TAG",t?.message) },
                {view.setAdapter(posts)
                view.hideProgressBar()}
        ))

我并没有完全强调如何使Observable.zip作为互联网上的例子没有明确解释。

问:如何更改我的代码以使Observable.zip正常工作?

1 个答案:

答案 0 :(得分:5)

您的zip应如下所示:

val observableZip : Observable<PostList> = Observable.zip(fb1,fb2, object : BiFunction<PostList, StriPostList, PostList> {
        override fun apply(t1: PostList, t2: PostList): PostList {
           // do the zipping
        }
    })
  1. zip参数的类型为Function BiFunction。只有可观察列表,然后是BiFunction(或者,一个ObservableSource和一个普通Function
  2. 使用Rx中的BiFunction非常重要,因此请务必使用import io.reactivex.functions.BiFunction 而不是 java.util.function.BiFunction