<@U8X1UM66N> example with single thread context yo...
# coroutines
s
@Jonathan example with single thread context you proposed
Copy code
fun main(args: Array<String>) {
    val context = newSingleThreadContext("test")
    launch(context) {
        withContext(context) {
            CompletableFuture.runAsync {
                print("Hello")
            }.await()
        }
    }
}

suspend fun <T> CompletableFuture<T>.await() = suspendCoroutine<T> { cont ->
    cont.resume(join())
}
Not working😮
j
You have to make the main thread waiting for the result
s
Yeah man I know that's why i was telling you it will not work.
j
Copy code
fun main(args: Array<String>) = runBlocking {
    val context = newSingleThreadContext("test")
    launch(context) {
        withContext(context) {
            CompletableFuture.runAsync {
                print("Hello")
            }.await()
        }
    }.join()
}
BTW there is already a better implementation of
CompletableFuture.await
in
kotlinx.coroutines-jdk8
Or if you don't want to
join
you can use parent-child relation:
Copy code
fun main(args: Array<String>) = runBlocking {
    val context = newSingleThreadContext("test")
    launch(coroutineContext + context) {
        withContext(context) {
            CompletableFuture.runAsync {
                print("Hello")
            }.await()
        }
    }
}
And you should close the thread context too.
s
Oh man, your code examples just avoiding problem that I trying to figure out how to solve properly😊
j
Sorry, I obviously don't understand what you want to achieve.
i
@stepango Then it's great, if you don't have a problem, you don't have to solve it. Seriously, `runBlocking`+`withContext` seems to be the way to go in your situation, judging on your original code example (handleAction)
s
@ilya.gorbunov But I don't have an option to wrap execution in
runBlocking
I just need right context to this construction to make
launch + withContext
run synchronously, thats it😊 So far
Unconfined
works as I expect, but is there any other context that would be more suitable for this?
j
@stepango Why cannot you use
runBlocking
? This function can be called from anywhere and anything can be called in the lambda. And even if
runBlocking
should generally be avoided, it is a first class choice when it comes to testing.
s
@Jonathan believe me it does not matter
Copy code
fun test(){
        smth(coroutineContext) // Unit
        //^not suspend function i can't change contains launch + withContext
}
I want to change coroutine context in the way that will make
smth
function to run synchronously
runBlocking will not help me here
j
Copy code
fun test() {
	newSingleThreadContext("test context").use { context ->	
		runBlocking(context) {
			smth(context) // Unit
			// no need to suspend
			// no need to change launch + withContext
		}
	}
}
Sorry, I still don't understand why
runBlocking
doesn't help.