Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen kotlin.collections.HashMap@3ee0f08 in KMM iOS

I'm using Kotlin 1.5.10, and ktor 1.6.0.

When I perform a network fetch

    private suspend fun getHello(): Model.Result {
        return httpClient.get("https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=multiplatform")
    }

With the data model

    object Model {
        @Serializable
        data class Result(val query: Query)
        @Serializable
        data class Query(val searchinfo: SearchInfo)
        @Serializable
        data class SearchInfo(val totalhits: Int)
    }

The Android version compiled fine and responded with

Result(query=Query(searchInfo=SearchInfo(totalhits=707)))

However, when I compiled it in iOS, it returns a crash

RESPONSE https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=multiplatform failed with exception: 
kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen kotlin.collections.HashMap@2566888

This StackOverflow recommend downloading down to 1.3.10, but I cannot do that as the KMM won't compile in my latest Android Studio 4.2.1. Besides, I don't use coroutine for the commonMain code (only in Android code).

This StackOverflow state issue with Kodein, but I don't use Kodein.

Note: my code is identical to https://www.youtube.com/watch?v=_Q62iJoNOfg, except that the model and the URL is different.

Anyone can recommend how we can get this issue resolve?

like image 341
Elye Avatar asked Mar 02 '23 13:03

Elye


1 Answers

I find an issue filed here https://github.com/Kotlin/kotlinx.serialization/issues/1450.

I tried one of the workaround i.e. useAlternativeNames = false for the Json serialization configuration, then it solve my issue

        install(JsonFeature) {
            val json = kotlinx.serialization.json.Json {
                ignoreUnknownKeys = true
                useAlternativeNames = false
            }
            serializer = KotlinxSerializer(json)
        }
like image 167
Elye Avatar answered May 07 '23 05:05

Elye