안드로이드 개발 팁 블로그

1. RxAndroid를 적용해보고 HelloWorld를 찍어보자. 본문

Rxandroid

1. RxAndroid를 적용해보고 HelloWorld를 찍어보자.

tiii 2016. 2. 18. 15:05
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.




2016/02/17 - [Rxandroid] - 0. RxAndroid의 시작


두번째 시간! 오늘은 Rx를 프로젝트에 적용하는 방법과 기본적인 HelloWorld를 해보자.



1. 새로운 프로젝트를 생성


새로운 프로젝트를 생성했으면 build.gradle에 Rxandroid 의존성을 추가하면 된다.

rxandroid는 rxjava에 의존성을 가지고 있기 때문에 rxandroid만 추가하면 되지만
rxjava가 업데이트 되어 rxandroid와 버전이 맞지 않을 경우 별도로 의존성을 추가할 수 있다.
지금은 Rxandroid는 1.1.0 이고 Rxjava는 1.1.1 이라 별도로 의존성을 추가해 줬다.
그리고 build.gradle 파일을 동기화 해주면 적용은 끝난다. 

1.0 이하 버전에서는 각종 컴포넌트의 이벤트를 처리 부분이 포함되어 있었으나 
라이브러리의 경량화와 유지보수등의 문제로 서드파티 라이브러리로 빼버렸다.


RxLifecycle - Lifecycle handling APIs for Android apps using RxJava
RxBinding - RxJava binding APIs for Android's UI widgets.
SqlBrite - A lightweight wrapper around SQLiteOpenHelper and ContentResolver which introduces reactive stream semantics to queries.
Android-ReactiveLocation - Library that wraps location play services API boilerplate with a reactive friendly API.
rx-preferences - Reactive SharedPreferences for Android

등이 있고 github를 찾아보면 Rx용으로 된 서드파티 라이브러리가 많이 있으니 참고 바란다.




2.HelloWorld를 찍어보자.
기본으로 만들어진 MainActivity에 간단한 예제를 만들어 보자.
 

이 예제를 실행하면 앱이 실행되면서 MainActivity의 Layout에 있는 TextView에 "Hello RxAndroid !!"가 찍히고 종료된다.



3.메모리 누수가 있다고!?
Rxandroid 는 메모리누수에 대한 문제점이 있는데 
Observable이 Context를 복사해서 유지하고 있기 때문에 엑티비티가 종료될 때 unsubscribe하지 않으면 안된다.

기본 예제에서는 명시적으로 onPause 나 onDestory에 Subscription의 unsubscribe()를 호출하도록 되어 있지만
서드파티 라이브러리(RxLifecycle)를 사용해서 적용해 보도록 해보자. 쉽게 쉽게 가자고...

프로젝트에 의존성을 추가한다.



엑티비티의 상속을 RxAppCompatActivity으로 변경하고 compose를 사용하여 Rxlifecycle을 적용해 줍니다.
onCreate 에서 subscribe을 하면 onDestory 에서 unsubscribe 되고 
onResume 에서 subscribe을 하면 onPause 에서 unsubscribe 됩니다.

참 쉽죠? 만약에 종료되는 시점은 바꾸고 싶다면 직접 bindUntilEvent 선언하여 조정할 수 있습니다.



4.코드를 좀 더 깔끔하게!!
Observable을 좀 더 쉽게 만들 수 있는 방법이 있습니다.
바로 미리 만들어둔 오퍼레이터를 사용하는 것 입니다.

  • just( ) — convert an object or several objects into an Observable that emits that object or those objects
  • from( ) — convert an Iterable, a Future, or an Array into an Observable
  • repeat( ) — create an Observable that emits a particular item or sequence of items repeatedly
  • repeatWhen( ) — create an Observable that emits a particular item or sequence of items repeatedly, depending on the emissions of a second Observable
  • create( ) — create an Observable from scratch by means of a function
  • defer( ) — do not create the Observable until a Subscriber subscribes; create a fresh Observable on each subscription
  • range( ) — create an Observable that emits a range of sequential integers
  • interval( ) — create an Observable that emits a sequence of integers spaced by a given time interval
  • timer( ) — create an Observable that emits a single item after a given delay
  • empty( ) — create an Observable that emits nothing and then completes
  • error( ) — create an Observable that emits nothing and then signals an error
  • never( ) — create an Observable that emits nothing at all

Observable을 만드는 오퍼레이터 목록이다. 각각의 사용법에 대해서는 나중에 설명하고
일단 simpleObservable는 String을 리턴하는 것 말곤 하는 일이 없으니까 이 중 just()를 사용하여 코드를 줄여 봅시다. 
Observable과 subscriber 를 하나로 합치고 Subscriber도 생성하지 않고 필요한 onNext만 처리하는 인터페이스를 사용하여 코드를 줄입니다.
상황에 따라서 onError나 onComplete를 처리해야 하는 경우도 있지만 지금 예제에서는 필요 없으니까요~




어때요~? 확 줄었죠..? 마지막으로 이것저것 라이브러리를 붙여서 더 줄여 봅시다.




5.RetroLambda 사용하기
Rx는 람다식과 만나면 더욱 코드를 줄일 수 있습니다.
예전에 포스팅했던 RetroLambda 적용하기(
http://tiii.tistory.com/5)를 참고하여 
프로젝트에 RetroLamda를 적용해 봅시다.
추가로 코드인젝션 라이브러리 버터나이프로 추가해 봅시다.

 buildscript {

repositories {
mavenCentral()
}

dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.3.0-beta4'
}
}
repositories {
mavenCentral()
}
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
applicationId "tiii.com.rxandroid"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'io.reactivex:rxandroid:1.1.0'
// Because RxAndroid releases are few and far between, it is recommended you also
// explicitly depend on RxJava's latest version for bug fixes and new features.
compile 'io.reactivex:rxjava:1.1.1'
compile 'com.trello:rxlifecycle:0.4.0'
compile 'com.trello:rxlifecycle-components:0.4.0'
compile 'me.tatarka:gradle-retrolambda:3.3.0-beta4' compile 'com.jakewharton:butterknife:7.0.1'
}




람다식과 버터나이프를 사용한 방법입니다.



다음엔 Rx에서 자주 사용되는 Operator의 사용법에 대해서 알아봅시다.

수고하세용~


'Rxandroid' 카테고리의 다른 글

Connectable Observable Operators  (0) 2016.05.26
3. Operators 이해하기 - 생성  (2) 2016.03.02
2. 스케쥴러 이해하기  (1) 2016.02.23
1-1. RxAndroid MVP Sample  (1) 2016.02.19
0. RxAndroid의 시작  (0) 2016.02.17
Comments