Hello, How can we create a Singleton in Kotlin whi...
# multiplatform
a
Hello, How can we create a Singleton in Kotlin which takes some parameters? The reason I am asking this in this channel is because in kotlin native we can not have var in an object class unless you annotate it with ThreadLocal. I am not sure how to save value in a member variables of a singleton object class.
t
AtomicReference
and annotate with
@SharedImmutable
a
I can not access AtomicReference in CommonMain
I am working on a Kotlin Multiplatform Mobile Project
t
you can use expect/actual to access it quite easily
you can also use the stately library
one way to do it without a library is to
expect
a
var
, and on Native implement get and set and redirect it to an
AtomicReference
a
ah, interesting. Let me try that
b
Another approach:
Copy code
class MyVarSingleton private constructor(
    val title: String,
    val description: String
) {

    @Suppress("VARIABLE_IN_SINGLETON_WITHOUT_THREAD_LOCAL")
    companion object {
        private var instance: MyVarSingleton? = null
        private val mutex = Mutex(false)

        suspend fun getInstance(): MyVarSingleton {
            mutex.withLock {
                return instance ?: throw AssertionError("Must call Init before getting instance")
            }
        }

        suspend fun setInstance(title: String, description: String) {
            if (instance != null) throw AssertionError("Can not re-initialize singleton instance")
            mutex.withLock {
                instance = MyVarSingleton(title, description)
            }
        }

    }
}
Thread safe singleton with a mutex and can be initialized with arguments
I would not suggest this as a good or best practice to be fair. I would instead suggest using environment variables, const definitions, or to have concurrent patterns such as an actor to produce and expose these values.
a
thanks for replying. I went down the route of using expect/ actual and storing the instance in AtomicReference and it worked.
454 Views