https://kotlinlang.org logo
Title
t

Tristan

02/13/2022, 11:37 PM
Hello, I am trying to understand how works the frozen concept. I have the following piece of code:
class UserRepository(
    private val userDataSource: UserDataSource,
    private val coroutineScope: CoroutineScope = CoroutineScope(Dispatchers.Default)
) {
    private val userMutex = Mutex()
    private var user: User? = null

    suspend fun fetch(userId: String): User? {
        println("Fetch user")
        println("context = " + coroutineContext) // prints Main

        if (user === null) {
            val result = withContext(coroutineScope.coroutineContext) {
                println("Switch context")
                println("context = " + kotlin.coroutines.coroutineContext) // prints Dispatched
                adsSdkConfigurationDataSource.getUser(userId)
            }

            publisherConfigurationMutex.withLock {
                println("Mutation")
                println("context = " + coroutineContext) // prints Main
                publisherConfigurationApiModel = result
            }
        }

        return publisherConfigurationMutex.withLock {
            publisherConfigurationApiModel
        }
    }
}
My logs look like
Instantiate UserRepository
context = [StandaloneCoroutine{Active}@2272df8, MainDispatcher]
Is UserRepository frozen? false

Fetch user
context = [StandaloneCoroutine{Active}@2272df8, MainDispatcher]

Switch context
context = [DispatchedCoroutine{Active}@3921848, WorkerCoroutineDispatcherImpl@2225538]

Mutation
context = [StandaloneCoroutine{Active}@2272df8, MainDispatcher]
Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException: mutation attempt of frozen com.me.UserRepository@227a228
Why after coming back to the context that created the
UserRepository
I cannot perform a mutation?
n

Nick Allen

02/14/2022, 3:11 AM
Please put large code blocks in a thread so the channel is easier to read. Frozen means immutable. It does not mean “read-only from other threads”.
#kotlin-native may be a better place to ask about native specific questions.
👍 1
j

Joffrey

02/14/2022, 8:35 AM
Also, note that there is a new memory model now, so you might want to try it out instead of (or in addition to) learning the frozen model, because eventually this will be obsolete. It depends on the type of project you're writing I guess.
t

Tristan

02/14/2022, 3:43 PM
Thanks for the answers. I read about the new model, but ran into other issues with Ktor. But I wanted to understand what was happening with freeze in my situation. Articles from TouchLab are saying I should identify what does the freeze. I have. But now I don’t understand how to get immutable again, even though I am in the same thread that created the instance of UserRepository