如何使用RxBinding&改造?

时间:2016-03-02 09:16:05

标签: rx-android retrofit2

这是我的代码:

// Observable from RxView
RxView.clicks(mBtnLogin)
            .throttleFirst(500, TimeUnit.MILLISECONDS)
            .subscribe(new Action1<Void>() {
                @Override
                public void call(Void aVoid) {
                    String userName = mEditUserName.getText().toString();
                    String passWord = mEditPassWord.getText().toString();

                    if (TextUtils.isEmpty(userName)) {
                        Toast.makeText(LoginActivity.this, R.string.input_user_name, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (TextUtils.isEmpty(passWord)) {
                        Toast.makeText(LoginActivity.this, R.string.input_pass_word, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    LoginAction action = Constants.retrofit().create(LoginAction.class);
                    // Observable from Retrofit
                    Observable<String> call = action.login(userName, MD5.encode(passWord));
                    call.subscribeOn(Schedulers.io())
                            .subscribe(new Observer<String>() {
                                @Override
                                public void onCompleted() {
                                    System.out.println("completed");
                                }

                                @Override
                                public void onError(Throwable e) {
                                    e.printStackTrace();
                                }

                                @Override
                                public void onNext(String s) {
                                    System.out.println("next" + s);
                                }
                            });
                }
            });

有什么方法可以将RxView中的Observable与改造后的Observable结合起来?

我认为代码很难看,并且不符合ReactiveX的规范。

1 个答案:

答案 0 :(得分:5)

是的,您可以使用.flatMap()运算符:

RxView.clicks(mButton)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<Void, Observable<Response>>() {
                    @Override
                    public Observable<Response> call(Void aVoid) {
                        return apiService.getResponse().subscribeOn(Schedulers.io());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
使用lambdas看起来会好一些:

RxView.clicks(mButton)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(aVoid -> apiService.getResponse().subscribeOn(Schedulers.io()))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();