paulex
01/28/2020, 9:26 AMfun main(args:Array<String>) = runBlocking<Unit>{
InternalLoggerFactory.setDefaultFactory(Log4JLoggerFactory.INSTANCE)
val server = AppServer(this)
server.run()
}
I want to main thread to stay alive until a shutdown...Erik
01/28/2020, 10:01 AMlaunch
your coroutine from a CoroutineScope
and join()
the Job
that launch
returns before the JVM exits.elizarov
01/28/2020, 10:14 AMAppServer
? You should check it out to see what facilities it provides to wait until shutdown.paulex
01/28/2020, 10:21 AM@Throws(InterruptedException::class)
fun blockUntilShutdown(){
this.server.awaitTermination()
}
This is the implementation of awaitTermination
@Override
public void awaitTermination() throws InterruptedException {
synchronized (lock) {
while (!terminated) {
lock.wait();
}
}
}
elizarov
01/28/2020, 10:23 AMrunBlocking
) here. Just use this awaitTermination
to block.paulex
01/28/2020, 10:23 AMlaunch {}
blocks are not triggered.elizarov
01/28/2020, 10:24 AMlaunch { … }
in some other dispatcher, because you’ve blocked your main thread by waiting, or block some other thread to wait for termination, and then you’ll be able to launch in your main thread.launch(Dispatchers.Default) { … }
The latter: withContext(<http://Dispatchers.IO|Dispatchers.IO>) { server.blockUntilShutdown() }
Either way it should work.paulex
01/28/2020, 10:26 AMClass ServiceA (val scope: CoroutineScope){
@Inject
private val repo: Repository
fun getFoo(id, callback){
scope.launch {
repo.getFooFromDatabase() //suspend function
}//end of scope
}//end of function
}//end of class
//Main Function
fun main(){
val serviceA = ServiceA(CoroutineScope(Dispatchers.Default));
…
appServer.awaitTermination();
}
I'm guessing this is not a bad practice, the way i have initialized CoroutineScope.. Thanks in advance