https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
p

pererikbergman

10/14/2021, 2:21 PM
Hey all, I have a big upcoming project and I am considering going KMM so I have been testing, playing learning for the last month or so. Most of my issues been solve no problem, but I can’t manage to find a solution for this: I want to be able to wrap any arbitrary library in androidApp and iosApp and inject it into shared, I tried to create a singleton where I would store this wrapper with no success. In commonMain I want to do this:
Copy code
object MySingleton {
    var myInterface: MyInterface? = null

    fun hello(msg:String) {
        myInterface?.hello(msg)
    }
}

interface MyInterface {
    fun hello(msg: String)
}
And then in androidApp
Copy code
MySingleton.myInterface = object : MyInterface {
    override fun hello(msg: String) {
        // do some magic
    }
}
And in iOS something like this:
Copy code
class MyInterfaceImpl : MyInterface {
    func hello(msg: String) {
        // do some magic
    }
}

 MySingleton.shared.myInterface = MyInterfaceImpl()
But it just crashes on iOS, no clear error message as well. Anyone have any suggestion on how to do this?
t

Trevor Stone

10/14/2021, 2:46 PM
Have you tried
actual/expect
p

pererikbergman

10/14/2021, 3:04 PM
I think they have to be in the same module, right ?
I need them to be in different modules.
m

Mejdi

10/14/2021, 4:34 PM
try to add this annotation to the object:
@ThreadLocal
on iOS (KMM) by default all singletons properties are freezed by default..so you cant mutate them. One way to avoid it is to mark it
@ThreadLocal
which means every thread will get its own copy and will be able to mutate it. Should not be any issue if you dont have multithreading.
👍 1
p

pererikbergman

10/15/2021, 1:36 AM
It kind of works but it also bet’s the purpose of having a singleton… I don’t want to think what thread it’s coming from… or maybe it’s OK since I use coroutines not threads… 🤔
m

Mejdi

10/15/2021, 5:11 AM
Yes that is my point..due to the limitations with the current multithreading model I hardly see ppl using heavily multiple threads. You will find yourself doing it in very specific cases. Another option is to use the multi-threading version if coroutines module.
p

pererikbergman

10/15/2021, 10:56 AM
Yeah, I will do some tests
2 Views