ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ReactiveX와 Retrofit 같이 쓰기!
    Android/RxJava 2019. 6. 18. 15:24

    Retofit의 Call 부분을 다시 되집어 보면 onFailure와 OnResponse가 있다

    어디선가 많이 본 형식인데


    맞다 ReactiveX와 비슷하게 생겼다!
    즉슨! 그말은 RxJav와 Retrofit을 함께 쓸 수 있지 않을까..?

    오늘은 두가지 방법으로 구현을 해볼 것이다

    1. 직접 코딩
    2. 라이브러리 사용


    Gradle Dependency

    // reactive
    implementation 'io.reactivex.rxjava2:rxjava:2.2.6'

    // retrofit2
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

    // okHttp3
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.2'


    먼저 이전 코드를 살펴보자

    GitHubClient().getService().getRepos("You-Kkomi") 
            .enqueue(object : Callback, retrofit2.Callback<List> { 
                override fun onFailure(call: Call<List>, t: Throwable) { 
                    Log.e("retrofit2", t.message) 
                } 
    
                override fun onResponse(call: Call<List>, response: Response<List>) { 
                    if (!response.isSuccessful) 
                        return 
    
                    response.body()!!.forEach { Log.d("retrofit2", it.name) } 
                } 
            }) 

    RxJava에서 Subject를 쓰면 간단하게 구현이 될 것 같다.

    class GtihubManager { 
    
        fun getRepoList(): BehaviorSubject<List> { 
    
            val behaviorSubject = BehaviorSubject.create<List>() 
    
            GitHubClient().getService().getRepos("You-Kkomi") 
                .enqueue(object : Callback, retrofit2.Callback<List> { 
                    override fun onFailure(call: Call<List>, t: Throwable) { 
                        behaviorSubject.onError(t) 
                    } 
    
                    override fun onResponse(call: Call<List>, response: Response<List>) { 
                        if (!response.isSuccessful) { 
                            behaviorSubject.onError(Exception("isNotSuccessful")) 
                            return 
                        } 
    
                        behaviorSubject.onNext(response.body()!!) 
                        behaviorSubject.onComplete() 
                    } 
                }) 
    
            return behaviorSubject 
        } 
    
    } 

    클래스 명은 생각이 나지 않아 대충 지었으니 그냥 넘어가도록하자..
    손쉽게 behavior를 사용하여서 코드를 작성해 보았다.

    GithubManager().getRepoList().subscribe { it.log() } 
    D/retrofit: [
    GitHubRepo(name=HF_Server),
    GitHubRepo(name=MC_DevLibrary),
    GitHubRepo(name=MC_DevLibrary1710),
    GitHubRepo(name=Refactoring-MVVM-using-AAC),
    GitHubRepo(name=You-Kkomi.github.io)
    ] 

    잘 들어온다...

    하지만 매번 rxjava를 쓰자고 저런식으로 말들어야 한다니... 매우 귀찮은 일이 아닐 수가 없다..
    그냥 call 쓰고말지...

    이를 Retrofit도 눈치를 차린건지 지원을 한다!
    그것도 단 1줄!

    class GitHubClient { 
    
        companion object { 
            val BASE_URL = "https://api.github.com" 
        } 
    
        fun getService(): GithubService { 
            return Retrofit.Builder() 
                .baseUrl(BASE_URL) 
                .addConverterFactory(GsonConverterFactory.create()) 
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 
                .build() 
                .create(GithubService::class.java) 
        } 
    
    } 

    끝?
    아니다 interface 부분도 변경해 주어야 한다.

    interface GithubService { 
    
        @GET("/users/{owner}/repos") 
        fun getRepos(@Path("owner") owner: String): Single<List> 
    
    } 
    GitHubClient().getService().getReposToSingle("You-Kkomi") 
            .subscribeOn(Schedulers.io()) 
            .observeOn(AndroidSchedulers.mainThread()) 
            .subscribe( 
                { repo -> repo.log() }, 
                { error -> error.log() } 
            ) 

    먼저 Retrofit작업은 백그라운드에서 시켜야 함으로 subscribeOn을 io로
    subscirbe는 데이터를 받아서 안드로이드 View에 쓸것임으로 Android의 mainThread로 받아준다.

    실행하면 아래와 같이 정상적으로 데이터가 들어오는 것을 볼 수 있다.

    D/retrofit: [
    GitHubRepo(name=HF_Server),
    GitHubRepo(name=MC_DevLibrary),
    GitHubRepo(name=MC_DevLibrary1710),
    GitHubRepo(name=Refactoring-MVVM-using-AAC),
    GitHubRepo(name=You-Kkomi.github.io)
    ] 

    손쉽게 구현을 한 Retrofit과 RxJava!

    댓글

Designed by Tistory.