Thread
#multiplatform
    p

    pererikbergman

    11 months ago
    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:
    object MySingleton {
        var myInterface: MyInterface? = null
    
        fun hello(msg:String) {
            myInterface?.hello(msg)
        }
    }
    
    interface MyInterface {
        fun hello(msg: String)
    }
    And then in androidApp
    MySingleton.myInterface = object : MyInterface {
        override fun hello(msg: String) {
            // do some magic
        }
    }
    And in iOS something like this:
    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?
    Trevor Stone

    Trevor Stone

    11 months ago
    Have you tried
    actual/expect
    p

    pererikbergman

    11 months ago
    I think they have to be in the same module, right ?
    I need them to be in different modules.
    Mejdi

    Mejdi

    11 months ago
    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.
    p

    pererikbergman

    11 months ago
    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… 🤔
    Mejdi

    Mejdi

    11 months ago
    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

    11 months ago
    Yeah, I will do some tests