Hi all :slightly_smiling_face:, forgive me if this...
# ktor
r
Hi all 🙂, forgive me if this is a trivial question, but I have a ktor server app and I need to run some suspendable functions to as the app initializes (s2specifically, I'm loading secrets from secrets manager and "caching" in memory to be used throughout the lifetime of the application server). Ideally these secrets need to be loaded before the server actually accepts requests. My initial approach was to do something like:
Copy code
environment.monitor.subscribe(ApplicationStarted) { app ->
    val secrets = app.getKoin().get<SecretsService>()

    // option 1
    runBlocking() {
        secrets.load() // this is a suspendable function
    }

    // option 2
    runBlocking(app.coroutineContext) { secrets.load() }

    // option 3
    val job = app.launch { secrets.load() }
    runBlocking { job.join() }
}
But i've read a lot of articles about how dangerous runBlocking can be, and honestly, i don't quite have a good enough mental model of how it works to really understand the implications / trade offs of different approaches. Would love any guidance on the specific problem but also general pointers on how to think about using runBlocking and coroutine contexts and such.
Additional context: i'm running kotlin 1.9.24 on the jvm 21 and ktor 2.3
l
I wouldn't say there is anything dangerous about runBlocking, it's just not efficient for use on every request. If this work only happens on app start, it should not be a big deal as the thread is unblocked as soon as your warmup logic is completed
a
Is it necessary to call the functions in the event handler or could they be called at application startup?
r
@Aleksei Tirman [JB], it is nice to have them in the event handler since i'm pulling the services from koin which is associated with my application, but it probably could be refactored to not be used within the event handler.
@Leo N my "dangerous" concerns around runBlocking come from the notes in the documentation, and also from reading several articles around runBlocking and causing deadlocks (as shown in this article - https://betterprogramming.pub/how-i-fell-in-kotlins-runblocking-deadlock-trap-and-how-you-can-avoid-it-db9e7c4909f1). But again, i'm new to this, so I'm still trying to build up my mental model of how it all works