Android

[Android] RxKotlin과 Retrofit2를 사용해 Github api 정보 가져오기

728x90

 

 

 RxKotlin과 Retrofit2를 사용하여 api 통신 하는 예제입니다. 예제에서는 Github에서 제공하는 api를 사용하여 사용자의 repository 정보들을 가져옵니다.

 

1. dependency 추가

 Rxkotlin과 Retrofit2 의존성을 app 수준의 gradle 파일에 추가해줍니다.

/* Retrofit2 */
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'

/* RxKotlin */
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'

 

 

2. permission 추가

 인터넷 사용을 위해 permission을 추가해줍니다.

<uses-permission android:name="android.permission.INTERNET"/>

 

 

3. client/GithubClient.class

class GithubClient {
    companion object {
        private const val BASE_URL = "https://api.github.com"

        fun getApi(): GithubService = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(OkHttpClient())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(GithubService::class.java)
    }
}

 

addCallAdapterFactory(RxJava2CallAdapterFactory.create())

위의 RxJava2CallAdapterFactory를 사용하는 이유는 기존의 Retrofit의 Call이라는 Response Type을 Rx의 Single 또는 Observable로 변환하기 위함입니다.

 

addConverterFactory(GsonConverterFactory.create())

위의 코드는 Json 형태로 전달 받는 Response를 사용자가 정의해놓은 인자들에 매칭시키기 위한 Converter입니다.

 

 

4. model/GithubRepo

 api를 통해 받아올 model을 정의합니다. 받아올 수 있는 필드들은 더 많지만 간단한 예제를 위해 이름, id, 생성 시간, url 정도만 받아옵니다.

data class GithubRepo(
    @SerializedName("name") val name: String,
    @SerializedName("id") val id: String,
    @SerializedName("created_at") val date: String,
    @SerializedName("html_url") val url: String
)

 

@SerializeName은 Annotation value에 해당하는 데이터를 변수에 바인딩합니다.

 

 

5. service/GithubService

service 클래스를 작성합니다. 아래의 예제는 사용자 id를 입력 받아 해당 사용자의 레파지토리들을 반환 받습니다.

interface GithubService {
    @GET("users/{owner}/repos")
    fun getRepos(@Path("owner") owner: String) : Single<List<GithubRepo>>
}

 

 

6. MainActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        GithubClient.getApi().getRepos("tkdgusl94")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe ({ items ->
                items.forEach { println(it) }
            }, { e ->
                println(e.toString())
            })
    }
}

 

결과

I/System.out: GithubRepo(name=android_ExpandableLayout, id=278224036, date=2020-07-09T00:35:15Z, url=https://github.com/tkdgusl94/android_ExpandableLayout)
    GithubRepo(name=Calendar, id=274086928, date=2020-06-22T08:52:07Z, url=https://github.com/tkdgusl94/Calendar)
    GithubRepo(name=chacha-springboot, id=234883870, date=2020-01-19T10:49:15Z, url=https://github.com/tkdgusl94/chacha-springboot)
    GithubRepo(name=chichi, id=247026553, date=2020-03-13T08:51:23Z, url=https://github.com/tkdgusl94/chichi)
    GithubRepo(name=CustomCalendarView, id=284726548, date=2020-08-03T14:46:16Z, url=https://github.com/tkdgusl94/CustomCalendarView)
    GithubRepo(name=DoItAndroidRev6, id=247196230, date=2020-03-14T02:14:30Z, url=https://github.com/tkdgusl94/DoItAndroidRev6)
    GithubRepo(name=Express-tutorial, id=210229601, date=2019-09-22T23:50:25Z, url=https://github.com/tkdgusl94/Express-tutorial)
I/System.out: GithubRepo(name=git-usage, id=196833769, date=2019-07-14T12:27:11Z, url=https://github.com/tkdgusl94/git-usage)
    GithubRepo(name=Interview_Question_for_Beginner, id=223688341, date=2019-11-24T03:43:12Z, url=https://github.com/tkdgusl94/Interview_Question_for_Beginner)
    GithubRepo(name=Jpa-shop, id=236153904, date=2020-01-25T10:13:33Z, url=https://github.com/tkdgusl94/Jpa-shop)
    GithubRepo(name=junior-recruit-scheduler, id=244580603, date=2020-03-03T08:25:05Z, url=https://github.com/tkdgusl94/junior-recruit-scheduler)
    GithubRepo(name=lecture-node-api, id=216728314, date=2019-10-22T05:13:56Z, url=https://github.com/tkdgusl94/lecture-node-api)
    GithubRepo(name=Lets-Study, id=230867861, date=2019-12-30T07:18:09Z, url=https://github.com/tkdgusl94/Lets-Study)
    GithubRepo(name=maven-with-jenkins, id=195183795, date=2019-07-04T06:41:26Z, url=https://github.com/tkdgusl94/maven-with-jenkins)
    GithubRepo(name=Riot-Crawler, id=229912059, date=2019-12-24T09:24:07Z, url=https://github.com/tkdgusl94/Riot-Crawler)
    GithubRepo(name=SNS_project, id=229910993, date=2019-12-24T09:17:22Z, url=https://github.com/tkdgusl94/SNS_project)
    GithubRepo(name=spring_boot_tutorial, id=231334113, date=2020-01-02T07:55:27Z, url=https://github.com/tkdgusl94/spring_boot_tutorial)
    GithubRepo(name=week-calendar, id=274854338, date=2020-06-25T07:27:02Z, url=https://github.com/tkdgusl94/week-calendar)
    GithubRepo(name=Yumi, id=229868511, date=2019-12-24T04:15:02Z, url=https://github.com/tkdgusl94/Yumi)

 

 

728x90