我是 KMM 和协程的新手。有没有一种方法可以等待异步函数的响应,而无需使依赖函数也挂起?
代码示例
// In HttpClient.kt in commonMain
class MyHttpClient {
val client = HttpClient()
suspend fun get(url: String): String {
client.get<String>(url)
}
}
// In Another class in commonMain
class Foo {
private val httpClient = MyHttpClient()
fun performAction() { <--- #1
val data = httpClient.get("server url")
// So stuff with that data after its retrieve from server.
}
}
// In iOS swift code
struct Example: View {
var body: some View {
Button {
foo.performAction() <--- #2
} label: {
Text("Click Me")
}
}
}
如果我将 #1 设为挂起函数 #2 需要不必要的回调。例子
// In iOS swift code
struct Example: View {
var body: some View {
Button {
foo.performAction(completionHandler: handler)
} label: {
Text("Click Me")
}
}
private func handler(response: KotlinUnit?, error: Error?) {
// DO NOTHING
}
}
我的单元测试也失败了,因为你不能让测试暂停功能并且runBlocking
不在 commonMain 中。