Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can i wait for another thread operator complete? (coroutine+Thread) #72

Closed
molixiaoge opened this issue Jun 16, 2017 · 5 comments
Closed

Comments

@molixiaoge
Copy link

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!

@fvasco
Copy link
Contributor

fvasco commented Jun 16, 2017

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

@elizarov
Copy link
Contributor

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

@molixiaoge
Copy link
Author

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!

@elizarov
Copy link
Contributor

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

@sr01
Copy link

sr01 commented Jul 4, 2018

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) }) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants