2021년 1월 30일 토요일

[RxAndroid] RxAndroid 사용해보자.

 RxJava가 대충(잉?) 알았으니 그걸 Android에서 어케 쓸까 참고해보자.

0. gradle에 라이브러리 추가


build.gradle (Module:...app) 파일에 rxjava2 추가
dependencies {
...
//Rx Utils dependencies
implementation 'io.reactivex.rxjava2:rxjava:2.2.19'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'

}

1.프로젝트 만들때 생성된 Activity에 간단히 RxJava(RxAndroid)를 사용해보자.

https://github.com/sugoigroup/rxandroid_sample/commit/8dbc80e9686850c20fa15003ef450218a0c99458

MainActivity의 onCreate

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected void onCreate(Bundle savedInstanceState) {
....
TextView helloTv = (TextView) findViewById(R.id.hello);
Observable.create((ObservableOnSubscribe<String>) emitter -> {
    emitter.onNext(getJest());
    emitter.onComplete();
})
        .subscribeOn(Schedulers.io()) //스케쥴러로 몰래 뒤에서 실행시키고
        .observeOn(AndroidSchedulers.mainThread())  //결과는 화면 메인쓰레드에서 하자.
        .subscribe(s -> helloTv.setText(s));


//just 는 아이템을 바로바로 서브스크들한테 방출한다.
Observable.just("Hello ! from just").subscribe(s -> helloTv.setText(s));
}
private String getJest() {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "Hello! from create";
}

2.버튼을 눌렀을때  한번에 두개의 텍스트뷰를 바꾸도록 해보자. Thread 대신 timer operator로 바꾸어보자.

https://github.com/sugoigroup/rxandroid_sample/commit/1d5171889342e24c78836b607563ee04c4fac396

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        helloTv = (TextView) findViewById(R.id.hello);
        helloTv2 = (TextView) findViewById(R.id.hello2);
        Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(e -> btnBlicked());
    }
    private void btnBlicked() {

        //timer 를 이용하면 앞서 했던 thread 를 안써도 일정시간 지난후 구독이 이루어지게 할수 있다..
        Observable.timer(3, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())  //결과는 화면 메인쓰레드에서 하자.
                .subscribe(d -> {
                    changeText(getJest());
                });


        //just 는 아이템을 바로바로 서브스크들한테 방출한다.
        Observable.just("Hello ! from just").subscribe(s -> changeText(s));
    }

    private void changeText(String txt) {
        helloTv.setText(txt);
        helloTv2.setText(txt);
    }

3. 옵서버에 구독아이템을 동적으로 추가해 보자

https://github.com/sugoigroup/rxandroid_sample/commit/23007802b49b21097228e1adec35f667259b9ee5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class MainActivity extends AppCompatActivity {
    private ConnectableObservable<String> dataStream;
    private Disposable disposable;

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

        TextView helloTv = (TextView) findViewById(R.id.hello);
        Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(e -> btnBlicked());

        dataStream = Observable.just("Hello ! from scriber" )
                .observeOn(AndroidSchedulers.mainThread())
                .publish();
        dataStream.subscribe(s -> helloTv.setText(s));

    }

    public void addMe(View view) {
        TextView helloTv2 = (TextView) findViewById(R.id.hello2);
        dataStream.subscribe(s -> helloTv2.setText(s));
    }

    private void btnBlicked() {
        disposable = dataStream.connect();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposable.dispose();
    }
}


참고 사이트들

버스도착정보 파싱 예제 : https://nittaku.tistory.com/215?category=727978

https://beomseok95.tistory.com/category/Rx




















0 comments:

댓글 쓰기