rx-android试用笔记(1)

最近微博不时看到有提到rx-java,联系到之前看到的reactjs,也就抽时间学习了一下,并一直在思考此种模式的优劣。目前得出的结论是:

** 优点**

  • 天然支持并发
  • 代码更易读

缺点

  • 抽象程度太过了(纠结中,觉得也算优点)
  • java语言上及android对其的支持上还不够(对比.NET)

今天就拿从ReactiveCocoa处看到的一个使用场景来练手,先上代码:

public class LoginActivity extends Activity {
    @InjectView(R.id.username)
    EditText usernameEditText;
    @InjectView(R.id.password)
    EditText passwordEditText;
    @InjectView(R.id.signin)
    Button signinButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ButterKnife.inject(this);

        Observable<Boolean> observableUsername =  WidgetObservable.text(usernameEditText).map(new Func1<OnTextChangeEvent, Boolean>() {
            @Override
            public Boolean call(OnTextChangeEvent onTextChangeEvent) {
                Boolean validateState = onTextChangeEvent.view().getText().length() > 6;
                if(!validateState) {
                    onTextChangeEvent.view().setError("length must great 6");
                }
                return validateState;
            }
        });

        Observable<Boolean> observablePassword =  WidgetObservable.text(passwordEditText).map(new Func1<OnTextChangeEvent, Boolean>() {
            @Override
            public Boolean call(OnTextChangeEvent onTextChangeEvent) {
                Boolean validateState = onTextChangeEvent.view().getText().length() > 3;
                if(!validateState) {
                    onTextChangeEvent.view().setError("length must great 3");
                }
                return validateState;
            }
        });


        Observable.combineLatest(observableUsername, observablePassword, new Func2<Boolean, Boolean, Boolean>(){
            @Override
            public Boolean call(Boolean validateStateUsername, Boolean validateStatePassword) {
                return validateStateUsername && validateStatePassword;
            }
        }).startWith(false).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean state) {
                signinButton.setEnabled(state);
            }
        });
    }
}

要在有lambda表达式的情况下,代码可更精简易读。

    原文作者:BingoStyle
    原文地址: https://www.jianshu.com/p/b2e6d93610a3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞