logo
down
shadow

Should be used a CoroutineScope's extension function or a suspending function


Should be used a CoroutineScope's extension function or a suspending function

Content Index :

Should be used a CoroutineScope's extension function or a suspending function
Tag : kotlin , By : Shawazi
Date : November 29 2020, 04:01 AM

this will help Answer to question 1:
No, you should not declare Repository#getRssChannel as an extension function of CoroutineScope, because you only invoke suspend functions but not start (launch/ async) new jobs. As @Francesc explained extension function of CoroutineScope should only start new jobs, but cannot return immediatly result and should not be declared as suspend by itself.

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to build a sequence from an external non-suspending function


Tag : kotlin , By : toki
Date : March 29 2020, 07:55 AM
will be helpful for those in need I'm afraid you're asking for the impossible. Kotlin doesn't implement coroutines through some backdoor JVM magic, but through the transformation of regular Java methods. Suspendable functions involve a hidden method signature change and their return type changes as well. Where your Visitor may have a method
void visit(Node)
Object visit(Node, Continuation)

When should I make my normal function suspending function?


Tag : kotlin , By : fstender
Date : March 29 2020, 07:55 AM
Hope this helps You want to offload CPU-intensive computation to a background thread so your GUI thread isn't blocked. You don't have to declare any suspending function to achieve that. This is what you need:
myActivity.launch {
    val processedList = withContext(Default) { processList(list) }
    ... use processedList, you're on the GUI thread here ...
}
suspend fun processList(list: List<String>): List<Info> = withContext(Default) {
    list.map { it.toInfo() }
}
fun String.toInfo(): Info = // whatever it takes

How to call Kotlin suspending coroutine function from Java 7


Tag : java , By : alchemist
Date : March 29 2020, 07:55 AM
To fix the issue you can do You have several options depending on your environment.
If you are using RxJava2 in the project, the module kotlinx-coroutines-rx2 has utility functions to convert back and forth between coroutines and Rx datatypes.
suspend fun sayHello(): String {
    delay(1000)
    return "Hi there"
}

fun sayHelloSingle(): Single<String> = GlobalScope.rxSingle { sayHello() }
abstract class Continuation<in T> : kotlin.coroutines.Continuation<T> {
    abstract fun resume(value: T)
    abstract fun resumeWithException(exception: Throwable)
    override fun resumeWith(result: Result<T>) = result.fold(::resume, ::resumeWithException)
}   
sayHello(new Continuation<String>() {
    @Override
    public CoroutineContext getContext() {
        return EmptyCoroutineContext.INSTANCE;
    }

    @Override
    public void resume(String value) {
        doSomethingWithResult(value);
    }

    @Override
    public void resumeWithException(@NotNull Throwable throwable) {
        doSomethingWithError(throwable);
    }
});

How to emit from a LiveData builder from a non-suspending callback function


Tag : kotlin , By : user186012
Date : March 29 2020, 07:55 AM
Hope this helps The solution involves wrapping the UrlRequest.Callback traditional callback structure in a suspendCoroutine builder.
I also captured my learning in a Medium article which discusses Cronet integration with LiveData and Kotlin Coroutines.
override suspend fun getLiveData(): LiveData<List<MyItem>> = liveData(coroutineDispatcher) {

    lateinit var result: List<MyItem>
    suspendCoroutine<List<MyItem>> { continuation ->

        val requestBuilder = cronetEngine.newUrlRequestBuilder(
            "http://www.exampleApi.com/example",
            object : UrlRequest.Callback() {

                // other callbacks not shown

                override fun onReadCompleted(request: UrlRequest?, info: UrlResponseInfo?, byteBuffer: ByteBuffer?) {
                    byteBuffer?.flip()
                    byteBuffer?.let {
                        val byteArray = ByteArray(it.remaining())
                        it.get(byteArray)
                        String(byteArray, Charset.forName("UTF-8"))
                    }.apply {
                        val myItems = gson.fromJson(this, MyItem::class.java)
                        result = myItems
                        continuation.resume(result)
                    }
                    byteBuffer?.clear()
                    request?.read(byteBuffer)
                },
                executor
        )
        val request: UrlRequest = requestBuilder.build()
        request.start()

    }
    emit(result)
}

Suspending function can only be called within coroutine body


Tag : android , By : Waynew
Date : March 29 2020, 07:55 AM
around this issue A Firestore snapshot listener is effectively an asynchronous callback that runs on another thread that has nothing to do with the coroutine threads managed by Kotlin. That's why you can't call emit() inside an asynchronous callback - the callback is simply not in a coroutine context, so it can't suspend like a coroutine.
What you're trying to do requires that you put your call to emit back into a coroutine context using whatever method you see fit (e.g. launch), or perhaps start a callbackFlow that lets you offer objects from other threads.
Related Posts Related QUESTIONS :
  • This annotation is not applicable to target member property without backing field or delegate
  • How to check if a string is a valid email in android?
  • Please Explain to me this kotlin statement?
  • How to use kotlin's default parameter only if the input is not null?
  • Proposed change of `equals` to `==` can't be applied to Char and String?
  • Issue when trying to import Jacoco code coverage to SonarQube: Cannot import coverage information for file, coverage dat
  • brief function code for null check in kotlin
  • How to capture an argument that was passed to a mocked function and return it?
  • Kotlin, unresolved reference on everything in VSCode
  • Webflux saving to repository without using .block()
  • takeWhile which includes the actual value matching the predicate (takeWhileInclusive)
  • Kotlin - object type check against HashMap<String, String> shows warning
  • Primitive properties initialization in Kotlin
  • How can I improve readability of this Kotlin code?
  • How to parse JSON objects into an enum
  • Can I get a TableView column to use a Kotlin Exposed transaction when referencing a property?
  • How can I perform clean up actions upon closing a view in Kotlin/TornadoFX?
  • How to deal with nullable variables that are not null?
  • Defining a mutable property with a custom setter
  • Kotlin combined usage of arrow, lamda, ?, . , and let. what it mean?
  • Is it possible to extend a base class in a data class without overriding parameters?
  • Access a value from a Kotlin script using jsr-223
  • Single method to launch a coroutine
  • The value of NumberPicker doesn't change
  • MutableSet don't prevent duplicated content when using sealed class
  • Why 'is' keyword only work with open classes in kotlin?
  • Extension function override of `equals(Any?): Boolean`
  • How to check a string starts with a specified string in kotlin?
  • Generate data class attribute value only during creation
  • Redirect to absolute URL in Ktor
  • how do I readirect t another path
  • How to limit allowed file size (multipart-file) in Ktor
  • nested let blocks in kotlin and valiadation
  • Generic method for finding instances of classes with 'is' operator
  • Enumerate the extension properties defined in a package
  • Unsubscribe observer in Async grpc stub - Java / Kotlin
  • How not pass some param in function
  • Using groupBy/groupingBy/aggregate to sum into smaller buckets in parallel?
  • Difference between get() and by lazy
  • Kotlin - force failing deserialization from json to class, when a non null property not exits in the json?
  • Room: Not sure how to convert a Cursor to this method's return type
  • Koin injecting into WorkManager
  • How to multiply all integer values in a Range in Kotlin?
  • Can I use coroutines in Kotlin when targeting JavaScript?
  • how to use the new extension functions in okhttp 4
  • using interface in kotlin
  • Getting "Suspension functions can be called only within coroutine body" when calling withContext(Dispatchers.M
  • Mocking extensions from Continuation
  • Zip 4 observables in kotlin
  • Property initializers are not allowed in interfaces
  • override and implement fn from class in interface
  • How to fix "[Dagger/MissingBinding]" in kotlin?
  • Run gradle vert.x in the command line
  • How do I create a parent-child relationship in immutable Kotlin classes
  • Provide instance without interface using Dagger
  • Kotlin ktor exposed DSL insert with reference
  • What does the AT symbol mean in KOTLIN
  • Efficiently make a view of (or copy) a subset of a large HashMap in Kotlin
  • SonarQube + Jacoco - Unable to read Koin module test coverage
  • Kotlin async/await syntax without blocking caller
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com