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)
}
}