Kotlinx.coroutines: How can i wait for another thread operator complete? (coroutine+Thread)

Created on 16 Jun 2017  路  5Comments  路  Source: Kotlin/kotlinx.coroutines

I want to write some coroutine code which will kill callback hell,with kotlinx.coroutines.Codes like this:

import kotlinx.coroutines.experimental.*
import kotlin.concurrent.*
import kotlinx.coroutines.experimental.channels.*


fun main(args: Array<String>) = runBlocking<Unit> {

val channel = Channel<Int>()

launch(context){

        thread(start = true) {  
        println("running from thread(): ${Thread.currentThread()}")
        channel.send(1)

    }

    channel.receive()
}

}

But which complie error

:Suspension functions can be called only within coroutine body

I know the error message means,But i want to ask if any object that can operator in another thread an can wait result in the coroutine?So i Can write sequence code which runs under callback!

Most helpful comment

Libraries that provide a single callback are easy to wrap for use with coroutines. It is explained here: https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#wrapping-callbacks

All 5 comments

thread(start = true) {  
    channel.send(1) <--- HERE?

you should wrap it in another runBlocking

You should look at async: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html

There is no reason to use thread with coroutines. Please, read the guide. It has a lot of working read-to-use examples that you can try: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md

But there are many Third party librarys,which use call back mode in their thread.With thread safe Wait result obj,the code will wrap easy!

Libraries that provide a single callback are easy to wrap for use with coroutines. It is explained here: https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#wrapping-callbacks

I use something similar with RxJava, for tests:

suspend inline fun <T> Observable<T>.suspend(): T = suspendCoroutine { cont -> this.take(1).subscribe({ cont.resume(it) }, { cont.resumeWithException(it) }) }

Was this page helpful?
0 / 5 - 0 ratings