我正在尝试构建一个简单的 Kotlin 多平台应用程序,该应用程序调用互联网以使用 ktor 从互联网获取一些字符串。我从中获取了一些功能Kotlin 会议应用 https://github.com/JetBrains/kotlinconf-app我编译了它,它在 Android 和 iOS 上都运行良好。
但是,在我的示例应用程序中,它仅适用于 Android,但在 iOS 上它会返回
kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen <object>@c422ffe8
这里是GitHub 存储库 https://github.com/LiewJunTung/Kotlin-Multiplatform-Example-App下面是我的代码:
// src/commonMain/CoroutinePresenter.kt
open class CoroutinePresenter(
private val mainContext: CoroutineContext, // TODO: Use Dispatchers.Main instead when it will be supported on iOS
private val baseView: BaseView
): CoroutineScope {
private val job = Job()
private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
baseView.showError(throwable)
}
override val coroutineContext: CoroutineContext
get() = mainContext + job + exceptionHandler
open fun onDestroy() {
job.cancel()
}
}
--
// src/commonMain/SamplePresenter.kt
class SamplePresenter(
val uiContext: CoroutineContext,
baseView: BaseView,
val sampleView: SampleView
) : CoroutinePresenter(uiContext, baseView) {
private val client = HttpClient()
fun callSimpleApi() {
try {
GlobalScope.launch(uiContext) {
getToolString()
}
} catch (e: Exception) {
sampleView.returnString(e.toString())
}
}
suspend fun getToolString() = client.get<String> {
url("https://tools.ietf.org/rfc/rfc1866.txt")
}
override fun onDestroy() {
super.onDestroy()
}
}
--
// src/iosMain/SampleIos.kt
object MainLoopDispatcher: CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
NSRunLoop.mainRunLoop().performBlock {
block.run()
}
}
}
--
// iosApp/iosApp/ViewController.swift
import app
class ViewController: UIViewController, SampleView, BaseView {
private lazy var presenter: SamplePresenter = { SamplePresenter(
uiContext: MainLoopDispatcher(),
baseView: self,
sampleView: self
)
}()
@IBOutlet weak var label: UILabel!
func showError(error: KotlinThrowable) {
print(error.message)
}
func returnString(result: String) {
label.text = result
print(result)
}
override func viewDidLoad() {
super.viewDidLoad()
print("helo")
presenter.callSimpleApi()
}
}