logo
Tags down

shadow

How to execute a blocking coroutine call in kotlin and specify the thread


By : Yesi
Date : September 09 2020, 11:00 PM
like below fixes the issue Is it possible to execute a blocking coroutine call (one that returns a value) while also providing the thread to execute the call on (I don't want to use the main thread, which is the default)? , I suppose you are looking for async(context):
code :
import kotlinx.coroutines.*

fun someCalc(): Int {
    println(Thread.currentThread().name) // Prints different thread
    Thread.sleep(500L)
    return 42
}

fun main() {
    val result = runBlocking {
        val deferred = async(Dispatchers.Default) {
            someCalc()
        }
        deferred.await()
    }
    println(result)
}
val result = runBlocking {
        withContext(Dispatchers.Default) {
            someCalc()
        }
    }


Share : facebook icon twitter icon

kotlin coroutine - how to ensure some commands run on UI main thread when invoked inside coroutine?


By : user2453226
Date : March 29 2020, 07:55 AM
To fix the issue you can do async creates a coroutine and runs in the Coroutine context, inherited from a CoroutineScope, additional context elements can be specified with context argument. If the context does not have any dispatcher nor any other ContinuationInterceptor, then Dispatchers.Default is used.
If Dispatchers.Default is used then whatever function you invoke in async builder it will run asynchronously. To switch contexts you can use withContext function:
code :
async {
    delay(5000)
    withContext(Dispatchers.Main) {
        // if we use `Dispatchers.Main` as a coroutine context next two lines will be executed on UI thread.
        doSomething()
        doAnotherThing()
    }
}
var job: Job = Job()
var scope = CoroutineScope(Dispatchers.Main + job)

scope.async {
    delay(5000) // suspends the coroutine without blocking UI thread

    // runs on UI thread
    doSomething() 
    doAnotherThing()
}

Is delay() In Kotlin Coroutine a non-blocking function?


By : user2572707
Date : March 29 2020, 07:55 AM
Does that help The Kotlin documentation often says "non-blocking" for suspending functions to make it clear that they don't block the current thread, but simply suspend the current coroutine.
So yes, delay is suspending and non-blocking.

kotlin coroutine withTimeout does not cancel when using withContext to get non-blocking code


By : Mike
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further After rereading the documentation on cancellation it seems coroutines have to cooperate to be cancellable:

Is it better to use a thread or coroutine in Kotlin?


By : user3261615
Date : March 29 2020, 07:55 AM
seems to work fine
My question is if I use Kotlin's coroutine, does it give better performance than thread?

Why and how Kotlin coroutine prevents blocking of a thread, even without "suspend" keyword?


By : aussie_a
Date : March 29 2020, 07:55 AM
Hope this helps Like post() on a View, launch() (usually) schedules work to be performed asynchronously with respect to the current bit of execution. So, the code in your lambda expression passed to launch() will be run on the main application thread eventually, just as the Runnable that you supply to post() will be run on the main application thread eventually. However, your onCreate() function will continue past the point of launch() to do whatever else it is supposed to.
However, just like a Runnable passed to post() could still tie up the main application thread due to what work it does in run(), your coroutine could still tie up the main application thread. It's just that this work would happen later than it would if you did the work directly in onCreate().
Related Posts Related Posts :
  • Kotlin, unresolved reference on everything in VSCode
  • brief function code for null check in kotlin
  • How to capture an argument that was passed to a mocked function and return it?
  • Issue when trying to import Jacoco code coverage to SonarQube: Cannot import coverage information for file, coverage dat
  • Proposed change of `equals` to `==` can't be applied to Char and String?
  • How to use kotlin's default parameter only if the input is not null?
  • Please Explain to me this kotlin statement?
  • How to check if a string is a valid email in android?
  • This annotation is not applicable to target member property without backing field or delegate
  • How to split on unicode whitespace in kotlin
  • How can Kotlin's Set be covariant when contains() takes E?
  • Kotlin inline class in JUnit tests
  • Lambda as a function parameter -> accept methods only from particular class
  • Kotlin - How do I concatenate a String to an Int value?
  • Why I Cannot Access to this function?
  • Kotlin test, how to run BeforeEach with DescribeSpec test style
  • Convince Kotlin compiler map has a key
  • how do you declare static property in kotlin?
  • How can i call an interface in kotlin?
  • Check if any array item is not empty
  • kotlin, where the return from inside the let go
  • Kotlin: Should mutableList be declared as Val or Var?
  • Convert Long to String in Kotlin
  • Extension property inside class: Unresolved reference: errorResponse
  • How to extend enums in Kotlin?
  • Idiomatic way in kotlin to transform/append to a list?
  • How to avoid nest 「null check」by "?.let"?
  • How to simply add another source to MediatorLiveData in kotlin?
  • Convert Set<Int> to varargs efficiently in Kotlin
  • Getting an error Using 'body(): ResponseBody?' is an error. moved to val with okhttp
  • Kotlin String to Int or zero (default value)
  • Return value only of the faster coroutine
  • Is there a Kotlin Coroutines Channel equivalent of RxJava's onDispose?
  • Create fat jar from kotlin multiplatform project
  • Short circuiting operation in Kotlin sequences
  • How to output deprecation warnings for Kotlin code?
  • Why does generated getter method have dollar signs in it?
  • For a final class why does when complain?
  • Reference value of constant with KDoc
  • How to create this coroutines in kotlin?
  • OkHttp: NoSuchMethodError copyInto in TlsUtil
  • Why do unreachable statements method not result in a compilation error?
  • Static/Const map key check at compile time
  • Escaping double quotes inside backticks
  • Does Kotlin have primitive types?
  • What is exactly null in kotlin and why i can't cause NPE with it?
  • Why would you use a Kotlin companion object rather than an initializer block for creation?
  • how to use operator overloading in Kotlin to divide a number by a numeric vector
  • How to use get() with backing fields in kotlin
  • How to map string to function and call it later
  • Kotlin enum constructor argument 'must be initialized' with companion object constant without qualifier name
  • Please explain to me class delegation in Kotlin
  • Error:(1, 41) Kotlin: Symbol is declared in module 'jdk.internal.opt' which does not export package 'jdk.i
  • How to properly make blocking service calls with Kotlin coroutines?
  • Gson SerializedName in a Kotlin interface
  • Kotlin convert FileTime to day, month, year
  • Kotlin how to move a file to a other directory?
  • If first param is true, then must pass second param in function
  • MutableLiveData for collections
  • How to replace long chain of forEach{} statements in Kotlin?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk