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

Kapil Godhwani

09/16/2019, 11:27 PM
Hello all, I started some basic implementations on Kotlin multiplatform and started following some amazing blogs written by everyone here. I am trying to implement a basic Service Locator that relies on a lateinit var. I dont see a way to initialize this var in my iOS Code and I also dont see the var in the native compiled code. Code -
Copy code
@ThreadLocal
object ServiceLocator {

    lateinit var applicationContext: ApplicationContext

    val CareApi by lazy { CareZoneApi(PlatformServiceLocator.httpClientEngine) }

    val performLogin: PerformLogin
        get() = PerformLogin(CareApi)

    val loginPresenter: LoginPresenter
        get() = LoginPresenter(performLogin, getUserSettings(applicationContext))

}
How do I access the
applicationContext
in my iOS app code to assign it a value. The ApplicationContext is my custom class. PS: Please let me know if this is also not the right place to ask this query.
a

alex009

09/17/2019, 2:16 AM
on iOS side you can't access to
ServiceLocator
instance, on iOS it will be
ServiceLocator().applicationContext = •••
...to avoid it you can create global function like:
Copy code
fun setupServiceLocator(context: ApplicationContext) {
    ServiceLocator.applicationContext = context
}
and on iOS side it will be:
Copy code
ServiceLocatorKt.setupServiceLocator(context: •••)
if file named ServiceLocator.kt (name of class with global functions generated from filename)
r

russhwolf

09/17/2019, 4:12 AM
Calling
ServiceLocator()
gives you the
ServiceLocator
instance. It looks like an initializer/method call but it’s always returning the same object.
🤔 1
☝️ 1
r

ribesg

09/17/2019, 9:02 AM
Yes,
ServiceLocator().x
on iOS in this case is identical to
ServiceLocator.x
on JVM/Android. I guess it’s this way because of some kind of limitations in the language translation.
k

Kapil Godhwani

09/17/2019, 12:20 PM
Yes even I thought so, but I am not able to access it in iOs code though. Now when I looked at it further, it is there in the
shared.h
header file in my imported framework, but it doesnt show up when I do
import shared
in my Viewcontroller. Which probably means some old shared framework is getting imported. Dont know from where though.
s

Sam

09/17/2019, 12:23 PM
Xcode can get confused sometimes. If everything seems like it should work but isn’t, first try clean. If that doesn’t help delete the derived data folder.
t

Tobi

09/18/2019, 9:06 AM
Why did you mark the
ServiceLocator
as
ThreadLocal
? I’ve seen this already a couple of time in other examples, but couldn’t figure out the reason 🤔
3 Views