Home > Mobile >  How do I perform a network process in a kotlin coroutine
How do I perform a network process in a kotlin coroutine

Time:02-15

I am attempting to run the getByName method in my android app, but have found that doing so in the main activity is cause for concern. I know I need to use coroutines, or async, or threads. But I'm not sure how to go about this. I'm somewhat self-taught with the software so forgive any obvious errors.

'''

class MainActivity : AppCompatActivity() {

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

    val adr = getIpStr()
    val serverAdr = "http://"   adr   ":5000"
    val myWebView: WebView = findViewById(R.id.webView)
    myWebView.webViewClient = WebViewClient()
    myWebView.loadUrl(serverAdr)
}

fun goToSettings(view: View) {
    val intent = Intent(this, SettingsActivity::class.java)
    startActivity(intent)
}

private suspend fun getIpStr(): String? {
    delay(2000L)
    return getByName("raspberrypi").hostAddress
}
}

'''

CodePudding user response:

You need to launch a coroutine using lifecycleScope:

lifecycleScope.launch {
    val adr = getIpStr()
    val serverAdr = "http://"   adr   ":5000"
    val myWebView: WebView = findViewById(R.id.webView)
    myWebView.webViewClient = WebViewClient()
    myWebView.loadUrl(serverAdr)
}

Alternatively, we can setup webview outside of launch():

val myWebView: WebView = findViewById(R.id.webView)
myWebView.webViewClient = WebViewClient()

lifecycleScope.launch {
    val adr = getIpStr()
    val serverAdr = "http://"   adr   ":5000"
    myWebView.loadUrl(serverAdr)
}

CodePudding user response:

You are getting exception because you starts your coroutine on main thread.

To perform network request,you need to use background thread .For that you can use " launch " coroutine builder with IO dispatcher to start new coroutine on background thread.

lifecycleScope.launch(Dispatchers.IO) {
val adr = getIpStr()
val serverAdr = "http://"   adr   ":5000"
//here switch to Main thread to Update your UI related task
withContext(Dispatchers.Main){     
myWebView.loadUrl(serverAdr)}
}
  • Related