4

I am trying to build a simple Kotlin Multiplatform app that calls to the internet to fetch some Strings from the internet with ktor. I took some functions from Kotlin conference app which I compiled and it works fine on both Android and iOS.

However, in my sample app, it only works on Android, but on iOS it returns

kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen <object>@c422ffe8

Here is the GitHub repository and below is my code:

// 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()
    }
}

Turns out that the Kotlin version 1.3.11 is causing the trouble. I have downgraded it to 1.3.10 and it works perfectly fine. ktor will receive a fix in the next minor release.

Source - Kotlin Slack, multiplatform channel.

4

1 回答 1

5

原来是 Kotlin 版本1.3.11造成了麻烦。我已将其降级为1.3.10,它工作得非常好。ktor 将在下一个次要版本中获得修复。

来源 - Kotlin Slack,多平台渠道。

于 2018-12-14T01:14:18.910 回答