처음부터 차근차근

Reactive programming(수정) 본문

프로그래밍/Android

Reactive programming(수정)

_soyoung 2022. 4. 22. 18:40
반응형

Reactive Programming

데이터 흐름과 전달에 관한 프로그래밍 패러다임

기존 PULL 방식이 아닌 PUSH 메커니즘

우리는 주로 절차를 명시하여 순서대로 실행되는 Imperative Programming(명령형 프로그래밍)을 한다. 

반면 Reactive Programming이란 데이터의 흐름을 먼저 정의하고 데이터가 변경되었을 때 연관된 작업이 실행된다. 즉 프로그래머가 어떠한 기능을 직접 정해서 실행하는 것이 아닌, 시스템에 이벤트가 발생했을 때 알아서 처리되는 것이다.

 

기존의 프로그래밍 방식을 Pull 방식, Reactive 프로그래밍 방식을 Push 방식이라고도 한다.
Pull 방식은 데이터를 사용하는 곳(Consumer)에서 데이터를 직접 가져와서 사용한다면,
Push 방식은 데이터의 변화가 발생한 곳에서 새로운 데이터를 Consumer에게 전달한다.

 

따라서 Reactive 프로그래밍은 주변 환경과 끊임없이 상호작용을 한다. 다만 프로그램이 주도하는 것이 아니라 환경이 변하면 이벤트를 받아 동작함으로써 상호작용한다

 

RxJava는 ReactiveX의 Java 언어 라이브러리로, 2013년 2월 넷플릭스에서 처음 소개하였다. 2016년 10월 RxJava2를 발표하였으며 가장 최근인 2020년 2월 RxJava3를 배포했다.

 

RxJava 간단한 예시

public class RxExample {
    public static void main(String[] args){
        Observable.just(10, 20, 30)
                .map(x -> x + 1)
                .subscribe(System.out::println);
  }
}

Observable : ReactiveX의 핵심 요소이자 데이터 흐름에 맞게 Consumer에게 알림을 보내는 Class이다.
just() : 가장 간단한 Observable 생성 방식이다. (생성 연산자라고도 한다)
map() : RxJava의 연산자이다. 데이터를 원하는 형태로 바꿀 수 있다.
subscribe() : Observable은 구독(subscribe)을 해야 데이터가 발행된다. 따라서 Observable을 구독하여 데이터를 발행 후, 수신한 데이터를 원하는 방식으로 사용(System.out::println)한다.

 

Reactive programming 실습하기 전 프로젝트 빌드 파일에다 의존성 관리 추가하기

app \ build.gradle 안에다 다음 코드 추가

// https://mvnrepository.com/artifact/io.reactivex.rxjava3/rxjava
implementation group: 'io.reactivex.rxjava3', name: 'rxjava', version: '3.1.4'

// https://mvnrepository.com/artifact/io.reactivex.rxjava3/rxandroid
implementation group: 'io.reactivex.rxjava3', name: 'rxandroid', version: '3.0.0'

rxjava와 rxadroid를 maven repository를 받는다.

 

이 코드 가져오는 곳 : https://mvnrepository.com/

여기서 rxjava, rxandroid 쳐서 선택한 후 gradle 클릭하고 복붙하기

 

 

예제1

public class MainActivity extends AppCompatActivity {

    private EditText edtLog;

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

        edtLog = (EditText) findViewById(R.id.edtLog);
        startRx();
    }

    private void startRx()
    {
        Observable<Integer> source = Observable.create(subscriber -> {
            try {
                for (int ii=0; ii < 5; ii++) {
                    subscriber.onNext(ii);
                }
                subscriber.onComplete();
            } catch (Exception e) {
                subscriber.onError(e);
            }
        });
        source.subscribe(
                ii -> edtLog.append("Next: " + ii + "\n"),    // onNext consumer
                e -> edtLog.append("Error: " + e),            // onError consumer
                () -> edtLog.append("Completed")              // onComplete action
        );
    }

}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="이벤트 결과값"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edtLog"
        android:layout_marginTop="20sp"
        android:gravity="top"
        android:textColor="#FF0000"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


</LinearLayout>

실행결과

 

 

 

 

예제2

public class MainActivity extends AppCompatActivity {

    private EditText edtLog;

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

        edtLog = (EditText) findViewById(R.id.edtLog);
        startRx();
    }

    private void startRx()
    {
        Observable<String> source = Observable.fromCallable( () -> "Welcome to Induk");
        source.subscribe(
                ii -> edtLog.append("Next: " + ii + "\n"),    // onNext consumer
                e -> edtLog.append("Error: " + e),            // onError consumer
                () -> edtLog.append("Completed")              // onComplete action
        );
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="이벤트 결과값"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/edtLog"
        android:layout_marginTop="20sp"
        android:gravity="top"
        android:textColor="#FF0000"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

실행결과

 

 

 

예제3

public class MainActivity extends AppCompatActivity {

    private EditText edtLog;

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

        edtLog = (EditText) findViewById(R.id.edtLog);
        startRx();
    }

    private void startRx()
    {
        Observable<String> source = Observable.just("event1", "event2").
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        source.subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
            }
            @Override
            public void onNext(@NonNull String s) {
                edtLog.append("Next: " + s + "\n");
            }
            @Override
            public void onError(@NonNull Throwable e) {
                edtLog.append("Error: " + e);
            }
            @Override
            public void onComplete() {
                edtLog.append("Completed");
            }
        });

    }
}

 

activity_main.xml은 전과 동일

실행결과

 

참고 : https://4z7l.github.io/2020/12/01/rxjava-1.html

출처 : 안드로이드프로그래밍(22-1학기)김용남교수 강의 내용 변형 및 요약

반응형

'프로그래밍 > Android' 카테고리의 다른 글

안드로이드 그래픽  (0) 2022.05.30
RxJava  (0) 2022.05.08
팝업 메뉴  (1) 2022.04.19
Android 메뉴  (0) 2022.04.12
리스너 객체  (2) 2022.04.08
Comments