티스토리 뷰

android

retrofit으로, rx and coroutine

노명규 2023. 2. 3. 15:23
class MainViewModel(val app: Application) : AndroidViewModel(app) {
    val tagtag = "tag@"

    val retrofit: RetrofitApi = RetrofitBuilder.getApiService("https://api.bithumb.com/")

    init {
        initCoinRx()
        initCoinCoroutine()
    }

    @SuppressLint("CheckResult")
    fun initCoinRx() {
        retrofit.getCoinInfoRx("BTC")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { coin ->
                Log.d(tagtag, "coin rx : ${coin.data.openingPrice}")
            }
    }

    var job: Job? = null

    @SuppressLint("CheckResult")
    fun initCoinCoroutine() {
        job = CoroutineScope(Dispatchers.IO).launch {
            val response = retrofit.getCoinInfoCoroutine("BTC")
            withContext(Dispatchers.Main) {
                if (response.isSuccessful) {
                    Log.d(tagtag, "coin coroutine : " + response.body()?.data?.openingPrice)
                    job?.cancel()
                }
            }
        }
    }
}

 

 

 

import io.reactivex.Single
import retrofit2.Response
import retrofit2.http.*

interface RetrofitApi {

    @GET("public/ticker/{path}")
    fun getCoinInfoRx(
        @Path("path") path:String?
    ):Single<CoinModel>

    @GET("public/ticker/{path}")
    suspend fun getCoinInfoCoroutine(
        @Path("path") path:String?
    ): Response<CoinModel>

}

 

 

 

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitBuilder {
    private fun getRetrofit(url: String?):Retrofit {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        val client = OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build()

        val retrofit = Retrofit.Builder().
                        baseUrl(url).
                        addConverterFactory(GsonConverterFactory.create()).
                        addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
                        client(client).build()

        return retrofit;
    }
    
    fun getApiService(url:String?) : RetrofitApi {
        return getRetrofit(url).create(RetrofitApi::class.java)
    }
}

'android' 카테고리의 다른 글

di 패턴, dagger, hilt  (0) 2023.04.04
system screen rotate click listener  (0) 2023.03.07
android mvvm 예제  (0) 2023.01.30
retrofit  (0) 2022.09.21
by viewmodels() 쓰는법,  (0) 2022.08.18