오늘도 삽질중

Android Rxbinding 과 combineLatest 를 사용해보자 본문

안드로이드

Android Rxbinding 과 combineLatest 를 사용해보자

Choi3950 2021. 1. 20. 16:50
반응형

RxBinding과 combinLatest 를 사용하여 간단한 Ui변경을 진행해보겠습니다.



에디트텍스트 2개와 , 체크박스 1개가 존재하고

에디트텍스트의 내용이 모두 존재하면서, 체크박스가 체크되어 있어야만 버튼이 활성화 됩니다.

3개 중 하나라도 충족이 안될경우 버튼이 비활성화 됩니다.




build.gradle( app Level )

2021.1.20 기준

implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
implementation 'io.reactivex.rxjava3:rxjava:3.0.6'
implementation 'io.reactivex.rxjava3:rxkotlin:3.0.1'
implementation 'com.jakewharton.rxbinding4:rxbinding:4.0.0'
implementation 'com.jakewharton.rxbinding4:rxbinding-material:4.0.0'





activity_sample.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:id="@+id/et_text_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="입력하세요1"
android:layout_marginTop="50dp"/>

<EditText
android:id="@+id/et_text_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/et_text_one"
android:hint="입력하세요2"
android:layout_marginBottom="20dp"/>

<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/et_text_two"
android:layout_marginBottom="20dp"
/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="확인"
android:layout_below="@id/checkbox"
android:enabled="false"
/>
</RelativeLayout>
</layout>





          SampleActivity.java Rx 구현부분


private fun viewInit() {

Observable.combineLatest(
binding.etTextOne.textChanges(),
binding.etTextTwo.textChanges(),
binding.checkbox.checkedChanges(), { t, t1 , t2->
binding.button.isEnabled = t.trim().isNotEmpty() && t1.trim().isNotEmpty() && t2
}).subscribe()

binding.button.clicks()
.throttleFirst(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.subscribe {
Log.e("TAG", "버튼클릭")
}

}




코드가 상당히 짧아졌습니다.

예전엔 리스너를 다 선언해서 모두 체크했어야 했는데 Rx를 공부하면서 감탄하는 경우가 점점 많아지네요.


combinLatest 함수 안에 t,t1,t2 가 뭔지 처음 보는 분들은 저게 뭔가...싶으실껍니다

저 또한 그랬으니까요.

처음 접하시는 분들에게 도움이 되고자 간단하게 설명해보면......


t 는 binding.etTextOne 의 텍스트 상태변경을 감지하여 값이 존재하면 true , 아닐경우 false를 반환합니다.

t1 는 binding.etTextTwo 의 텍스트 상태변경을 감지하여 값이 존재하면 true , 아닐경우 false를 반환합니다.

t2 는 binding.checkbox 가 체크되어 있다면 true , 체크해제시 false 를 반환합니다.


그래서 총 3가지의 조건이 충족되면 버튼이 활성화되고, 그렇지 않으면 비활성화로 변경됩니다.


말보다 직접 실행해서 확인해보시면 바로 이해가 되실겁니다.









반응형
Comments