Barend
11/02/2018, 9:40 AMGlobalScope.launch(Dispatchers.Main)
throw a Fatal Exception: android.os.NetworkOnMainThreadException
and GlobalScope.async
doesn't?Jean Mainguy
11/02/2018, 9:42 AMCoroutineScope(Dispatchers.Main).launch
?
See here: https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#0gildor
11/02/2018, 9:47 AMBarend
11/02/2018, 9:58 AMgildor
11/02/2018, 9:59 AMBarend
11/02/2018, 9:59 AMgildor
11/02/2018, 9:59 AMawait()
you will never know about this errorgildor
11/02/2018, 10:00 AMgildor
11/02/2018, 10:00 AMCan you elaborate on “You MUST NOT forget about the coroutine you’ve started with async”? Are there gotchas that one wouldn’t expect for example?
An uncaught exception inside the async code is stored inside the resulting Deferred and is not delivered anywhere else, it will get silently dropped unless processed.
If you forget the result of async than it will finish and will be garbage collected. However, if it crashes due to some bug in your code, you’ll never learn about that. That is why
Barend
11/02/2018, 10:00 AMval addJob = GlobalScope.async {
val hostAddress: String
val ip = InetAddress.getByName(hostName)
hostAddress = ip.hostAddress
addIPToMap(hostAddress)
}
runBlocking {
addJob.join()
}
gildor
11/02/2018, 10:01 AMBarend
11/02/2018, 10:07 AMgildor
11/02/2018, 10:09 AMlaunch
gildor
11/02/2018, 10:10 AM.await()
instaed of join, to handle result or errorsBarend
11/02/2018, 10:13 AMgildor
11/02/2018, 10:16 AMlaunch
you should wrap code to try/catch or runCatching
and handle result of operation, otherwise in case of error you application will crashgildor
11/02/2018, 10:17 AMNetworkOnMainThreadException
happens there because you do network requesst (lookup ip address) on the main thread, to avoid this use <http://Dispatchers.IO|Dispatchers.IO>