简体   繁体   中英

Kotlin: lag in coroutine runBlocking

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(){

        }

     }

 }

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM