I want to use Kotlin(v1.3.0) coroutines & java.nio.channels.SocketChannel (NIO) to replace Socket connect
(blocking IO) in Android. because this can save many number of threads.
The code below can't run because of job.await()
is suspending function in Kotlin, It just can be called in Ktolin coroutines block. like launch{..}
, async{..}
.
// this function will be called by Java Code
fun connect(address: InetSocketAddress, connectTimeout: Int): SocketChannel {
// Start a new connection
// Create a non-blocking socket channel
val socketChannel = SocketChannel.open()
socketChannel.configureBlocking(false)
// async calls NIO connect function
val job = GlobalScope.async(oneThreadCtx) {
aConnect(socketChannel, address)
}
// I what to suspend(NOT block) current Java Thread, until connect is success
job.await()
return socketChannel
}
But, I tried to use runBlocking{..}
make this function as normal function in Java. but job.await
blocked current Java Thread, Not suspend.
so, how should I implement this function with Kotlin(v1.3.0) coroutines?