Mario Andhika
10/17/2025, 7:04 AMobject MyObject {
var x = 1
init {
GlobalScope.launch {
x++
}
}
}
suspend fun main() = coroutineScope {
println(MyClass.x.toString()) // output: 1
delay(100L)
println(MyClass.x.toString()) // output: 2
}
How to make MyClass.x.toString() print 2 without needing to have a delay statement? How should I change the init block?Dmitry Khalanskiy [JB]
10/17/2025, 7:13 AMMario Andhika
10/17/2025, 7:25 AMDmitry Khalanskiy [JB]
10/17/2025, 7:26 AMrunBlocking can call suspend functions from blocking code. Is that what you're looking for?Mario Andhika
10/17/2025, 7:33 AMrunBlocking but it doesn’t seem to be available in my projectDmitry Khalanskiy [JB]
10/17/2025, 7:35 AMrunBlocking is available for JVM and Native, but not for JS or Wasm/JS. Are you targeting JS?Mario Andhika
10/17/2025, 7:39 AMDmitry Khalanskiy [JB]
10/17/2025, 7:41 AMsuspend Wasm/JS code block while waiting for something, unfortunately. This means that you need to obtain x first before constructing the classes depending on it.Mario Andhika
10/17/2025, 7:42 AMMario Andhika
10/17/2025, 8:06 AMdefaultRequest block, which is not a suspend blockDmitry Khalanskiy [JB]
10/17/2025, 8:17 AMgildor
10/17/2025, 8:30 AMgildor
10/17/2025, 8:31 AMMario Andhika
10/17/2025, 9:19 AMinit {
runBlocking {
val url = MainScope().async {
return@async fetchUrlFromResource()
}.await()
initKtor(url)
}
}
fun initKtor(defaultUrl: String)
suspend fun fetchUrlFromResource(): Stringgildor
10/17/2025, 9:20 AMgildor
10/17/2025, 9:22 AMsuspend fun createKtorClient(): HttpClient {
val defaultUrl = fetchUrlFromResource()
return HttpClient(...) {
defaultRequest {
url(defaultUrl)
}
}
}Mario Andhika
10/17/2025, 9:50 AMprivate var ktor: HttpClient? = null
init {
CoroutineScope(Dispatchers.Default).launch {
ktor = createKtorClient()
}
}
suspend fun getKtor(): HttpClient {
while(ktor == null) {
delay(100)
}
return ktor!!
}Dmitry Khalanskiy [JB]
10/17/2025, 9:56 AMinit block shouldn't be called) until you already have an HttpClient.gildor
10/17/2025, 12:57 PMgildor
10/17/2025, 1:02 PMclass HttpProvider(scope: CoroutineScope) {
private val httpClient = scope.async {
val defaultUrl = fetchUrlFromResource()
return HttpClient(...) {
defaultRequest {
url(defaultUrl)
}
}
suspend fun httpClient(): HttpClient {
return httpClient.await()
}
}Mario Andhika
10/18/2025, 11:25 AMgildor
10/18/2025, 11:57 AM