[안드로이드] 네트워크-OkHttp(Coroutine)

나고수·2021년 9월 8일
0

andriod

목록 보기
8/27
post-thumbnail

OkHttp 라이브러리를 코루틴을 이용해서 비동기적으로 실행하기 실습

참고 - 센치한개발자

//OkHttpCorutineActivity.kt

class OkHttpCorutineActivity : AppCompatActivity() {
    private lateinit var binding: ActivityOkHttpCorutineBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityOkHttpCorutineBinding.inflate(layoutInflater)
        setContentView(binding.root)

        coroutine()
        //getHtmlStr()
    }

    fun coroutine() {
        CoroutineScope(Dispatchers.Main).launch {

            //백그라운드 쓰레드에서 네트워크 통신을 한다음에(await로 백그라운드 쓰레드가 완료될때까지 기다림)
            val html = CoroutineScope(Dispatchers.IO).async {
                getHtml()
            }.await()
            //백그라운드 쓰레드의 동작이 끝나면 메인쓰레드에서 ui업데이트를 한다.
            binding.txt.text = html
        }

    }

    fun getHtml(): String {
        //1.클라이언트를 만들기
        val clinet = OkHttpClient.Builder().build()
        //2.요청만들기
        val req = Request.Builder().url("https://www.google.com").build()
        //3.응답받기 - execute방식은 동기방식임
        //따라서 코루틴의 scope(dispatcher.IO)안에서 실행시켜줘야한다.
        clinet.newCall(req).execute().use { response ->
            return if (response.body != null) {
                response.body!!.toString()
            } else {
                "body is null"
            }
        }
    }

    fun getHtmlStr() {
        //1.클라이언트를 만들기
        val clinet = OkHttpClient.Builder().build()
        //2.요청만들기
        val req = Request.Builder().url("https://www.google.com").build()
        //3.응답받기 - enqueue방식은 비동기방식임
        clinet.newCall(req).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                TODO("Not yet implemented")
            }

            override fun onResponse(call: Call, response: Response) {
                //enqueue는 비동기방식이라 알아서 백그라운드 쓰레드에서 진행이 되지만,
                //메인쓰레드의 ui를 변경해주려면, 메인쓰레드에서 코루틴을 실행시켜줘야한다.
                CoroutineScope(Dispatchers.Main).launch {
                    binding.txt.text = response.body!!.toString()
                }
            }
        })
    }
}
//OkHttpCorutineActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".OkHttpCorutineActivity">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>```
profile
되고싶다

0개의 댓글