如何在RXJava / Android中连接两个订阅

时间:2016-07-27 10:00:09

标签: java android android-edittext rx-java rx-android

如何绑定两个订阅,例如:

1)Retrofit& RX将JSON转换为recyclerView中显示的字符串列表。

    restClient.getCatFacts()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<CatFactsResponse>() {
                @Override
                public void onCompleted() {
                    Log.i(TAG, "onCompleted");
                }

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

                @Override
                public void onNext(CatFactsResponse catFactsResponse) {
                    catFactsList = catFactsResponse.getCatFacts();
                }
            });

2)Jack Wharton的RxBinding库对EditText小部件中的更改作出反应。

subscription = RxTextView
            .textChangeEvents(editText)
            .debounce(400, TimeUnit.MILLISECONDS)
            .observeOn(Schedulers.newThread())
            .subscribe(new Observer<TextViewTextChangeEvent>() {
                @Override
                public void onCompleted() {
                    Log.i(TAG, "onCompleted");
                }

                @Override
                public void onError(Throwable e) {
                    Log.i(TAG, "onError >> " + e.getMessage());
                }

                @Override
                public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) {
                    Log.i(TAG, textViewTextChangeEvent.text().toString());
                }
            });

获取使用EditText动态过滤的列表。我应该使用像Subject这样的类吗?如果是,那它应该怎么样?感谢您的帮助:)

1 个答案:

答案 0 :(得分:1)

您应该使用flatMap运算符

    subscription = RxTextView
            .textChangeEvents(editText)
            .debounce(400, TimeUnit.MILLISECONDS)
            .map(new Func1<TextViewTextChangeEvent, String>() {
                @Override
                public String call(TextViewTextChangeEvent textViewTextChangeEvent) {
                    return textViewTextChangeEvent.text();
                }
            })
            .flatMap(new Func1<String, Observable<CatFactsResponse>>() {
                @Override
                public Observable<CatFactsResponse> call(String text) {
                    return restClient.getCatFacts(text)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread());
                }
            })
            .subscribe(...);