Using coroutine to access internet

You must update UI in UI thread.

You must access internet beyond UI thread.

That's the Android's rule.
You can use coroutine to achieve this elegantly.

Don't forget declare permissions

    
    
    
    
//define a button's function
fun myBtnClick(view: View) {
        //using the UI thread in the outer coroutine
        GlobalScope.launch(Dispatchers.Main) {
            my_text.text = fromNetAsync("https://www.baidu.com").await()
       }
    }

private fun fromNetAsync(str : String) : Deferred{
        //异步也叫并发
        // It uses a common pool of shared background threads. 
        return GlobalScope.async {
            URL(str).readText()
        }
    }

你可能感兴趣的:(Using coroutine to access internet)