Reputation: 1067
I am using kotlin Coroutines to perform async network operations to avoid NetworkOnMainThreadException
.
The problem is the lag that happens when i use runBlocking
,that take sometime to complete current thread.
How can i prevent this delay or lag,and allow the async operation to be done without delay
runBlocking {
val job = async (Dispatchers.IO) {
try{
//Network operations are here
}catch(){
}
}
}
Upvotes: 1
Views: 1078
Reputation: 6505
By using runBlocking
you are blocking the main thread until the coroutine finishes.
The NetworkOnMainThread
exception is not thrown because technically the request is done on a background thread, but by making the main thread wait until the background thread is done, this is just as bad!
To fix this you could launch
a coroutine, and any code that depends on the network request can be done inside the coroutine. This way code may still be executed on the main thread, but it never blocks.
// put this scope in your activity or fragment so you can cancel it in onDestroy()
val scope = MainScope()
// launch coroutine within scope
scope.launch(Dispachers.Main) {
try {
val result = withContext(Dispachters.IO) {
// do blocking networking on IO thread
""
}
// now back on the main thread and we can use 'result'. But it never blocked!
} catch(e: Exception) {
}
}
If you don't care about the result and just want to run some code on a different thread, this can be simplified to:
GlobalScope.launch(Dispatchers.IO) {
try {
// code on io thread
} catch(e: Exception) {
}
}
Note: if you are using variables or methods from the enclosing class you should still use your own scope so it can be cancelled in time.
Upvotes: 2