<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zahra Heydari on Medium]]></title>
        <description><![CDATA[Stories by Zahra Heydari on Medium]]></description>
        <link>https://medium.com/@ZahraHeydari?source=rss-a3bb29fe186------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a-OtL8Ocih3s4dg10EUjcw.jpeg</url>
            <title>Stories by Zahra Heydari on Medium</title>
            <link>https://medium.com/@ZahraHeydari?source=rss-a3bb29fe186------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 06:03:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ZahraHeydari/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kotlin MultiPlatform (KMP)]]></title>
            <link>https://medium.com/@ZahraHeydari/kotlin-multiplatform-kmp-4799fdfb69f1?source=rss-a3bb29fe186------2</link>
            <guid isPermaLink="false">https://medium.com/p/4799fdfb69f1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Zahra Heydari]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 09:50:39 GMT</pubDate>
            <atom:updated>2024-06-05T09:50:39.068Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a step-by-step guide to creating your first cross-platform application that works on Android and iOS platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fx-vklX3CUgZ2ObLfI3QUA.png" /></figure><p>Kotlin Multiplatform technology simplifies the development of cross-platform projects and one of its major use cases is sharing the application logic code between platforms.</p><blockquote><strong>Note</strong>: This article is based on the sample project I implemented and published as a public repository on my GitHub. Please check the link below before starting the implementation.</blockquote><p><a href="https://github.com/ZahraHeydari/Kotlin-MultiPlatform-Mobile">https://github.com/ZahraHeydari/Kotlin-MultiPlatform-Mobile</a></p><h3>What we will learn in this article:</h3><ol><li><em>Setting Up The Environment</em></li><li><em>Creating a basic KMM Project</em></li><li>Understanding the basics of the KMM project structure</li><li><em>ViewModel</em></li><li><em>Networking</em></li><li><em>Coroutines in Ios</em></li><li><em>Dependency Injection</em></li></ol><blockquote><strong>Note</strong>: Before starting, you have to <a href="https://www.jetbrains.com/help/kotlin-multiplatform-dev/multiplatform-setup.html">set up an environment</a> for cross-platform development. But if you did it before, you can skip this step!</blockquote><h3>1. Setting up the environment</h3><p>Install the necessary tools:</p><ul><li><a href="https://developer.android.com/studio">Android Studio</a></li><li><a href="https://apps.apple.com/us/app/xcode/id497799835">Xcode</a></li><li><a href="https://www.oracle.com/java/technologies/javase-downloads.html">JDK</a></li><li><a href="https://kotlinlang.org/docs/multiplatform-plugin-releases.html">Kotlin Multiplatform Mobile plugin</a></li><li><a href="https://kotlinlang.org/docs/releases.html#update-to-a-new-release">Kotlin plugin</a></li></ul><p>To ensure everything works as expected, install and run the <a href="https://github.com/Kotlin/kdoctor#installation">KDoctor</a> tool.</p><pre>brew install kdoctor</pre><blockquote><strong>Note</strong>: <a href="https://github.com/Kotlin/kdoctor#installation"><strong>KDoctor</strong></a> works on macOS only.</blockquote><h3>2. Create a basic KMM project</h3><p>Open Android Studio and then select Kotlin Multiplatform App from the New Project templates. Click the Next button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4mBMWNG_E0hO5QcyVdq8sw.png" /></figure><p>On the next screen, choose a name for the application and the location for saving the project, etc. Click the Next button then.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIOTkb5PPJFMkRWtPn02jA.png" /></figure><p>Finally, select the dependency manager for the iOS app, which isRegular framework by default, and then hit the Finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzRF4ssLdSOb_GKbvkwnuQ.png" /></figure><p>Once gradle sync is complete, we can run both iOS and Android apps using the run button from the toolbar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lK3p84uBM7VQ5MyWPp7hFg.png" /></figure><p>That will run the app on the Android emulator or iOS simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fLTj5MmWcV-TFBk2bEPWMg.jpeg" /></figure><h3>3. Understanding the basics of the KMM project structure</h3><p>Each Kotlin Multiplatform project includes three modules shared, androidApp, and iosApp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*OmCqquHs3mnEe1HM_dvMdQ.png" /></figure><ul><li><strong>shared</strong> is a Kotlin module that contains the logic common for both Android and iOS applications — the code you share between platforms. It uses <a href="https://kotlinlang.org/docs/gradle.html">Gradle</a> as the build system to help automate your build process.</li><li><strong>androidApp</strong> is a Kotlin module that builds into an Android application. It uses Gradle as the build system. The androidApp module depends on and uses the shared module as a regular Android library.</li><li><strong>iosApp</strong> is an Xcode project that builds into an iOS application It depends on and uses the shared module as an iOS framework. The shared module can be used as a regular framework or as a <a href="https://kotlinlang.org/docs/native-cocoapods.html">CocoaPods dependency</a>.</li></ul><blockquote>💡 By default, the Kotlin Multiplatform wizard creates projects that use the regular framework dependency.</blockquote><h3>Expected and actual Keywords</h3><p><a href="https://kotlinlang.org/docs/multiplatform-expect-actual.html"><strong>Expected and actual declarations</strong></a> allow you to access platform-specific APIs from Kotlin Multiplatform modules. You can provide platform-agnostic APIs in the common code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwnaY-yN-aO_PHbWFkfeig.png" /></figure><p>To define expected and actual declarations, follow these rules:</p><ol><li>In the common source set, declare a standard Kotlin construct. This can be a function, property, class, interface, enumeration, or annotation.</li></ol><p>2. Mark this construct with the expect keyword. This is your expected declaration. These declarations can be used in the common code, but shouldn&#39;t include any implementation. Instead, the platform-specific code provides this implementation.</p><p>3. In each platform-specific source set, declare the same construct in the same package and mark it with the actual keyword. This is your actual declaration, which typically contains an implementation using platform-specific libraries.</p><blockquote>💡 During compilation for a specific target, the compiler tries to match each actual declaration it finds with the corresponding expected declaration in the common code.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4qEPOikVqwPcP4Vv01Caw.png" /><figcaption>The expected declaration in the common code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kh8QnrQwk-hSpEwWTEWeDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LO0VSYAPNGNcpQlpoqc1Mw.png" /><figcaption>The actual declarations in Android and iOS platforms</figcaption></figure><h4>Common code</h4><p>Common code is the Kotlin code shared among different platforms.</p><p>Consider the simple example:</p><pre>class Greeting {<br>    private val platform: Platform = getPlatform()<br><br>    fun greet(): String {<br>        return &quot;Hello, ${platform.name}!&quot;<br>    }<br>}</pre><pre>interface Platform {<br>    val name: String<br>}<br><br>expect fun getPlatform(): Platform</pre><h4>Share code on all platforms</h4><p>If you have business logic that is common for all platforms, you don’t need to write the same code for each platform — just share it in the common source set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xfhWoRu0UdQOUf6W.png" /></figure><p>You often need to create several native targets that could potentially reuse a lot of the common logic and third-party APIs.</p><p>Now it’s time to add viewModel to our KMM project!</p><h3><em>4. ViewModel in a KMP project</em></h3><p><a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModel"><strong>ViewModel</strong></a> is a class that is responsible for preparing and managing the data for an Activity or a Fragment.</p><p>In this sample project, EmojiHubViewModel is used to prepare and manage emoji data and expose it to the UI and SharedViewModel is a base for multiple viewmodels.</p><p>Both SharedViewModel and EmojiHubViewModel are in the commonMain module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*SQShjh6F26vQ7rwaeAqyzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*eEUct63vGp8_MmzO5MFTAA.png" /><figcaption>SharedViewModel and EmojiHubViewModel classes in the commonMain</figcaption></figure><pre>// shared/commonMain/.../viewModel/SharedViewModel<br>expect open class SharedViewModel() {<br><br>    val sharedViewModelScope: CoroutineScope<br><br>    protected open fun onCleared()<br>}</pre><p>In the <strong>androidMain</strong> and <strong>iosMain</strong> source sets, mark the same construct with the actual keyword. This actual declaration typically contains an implementation using platform-specific libraries.</p><p>Notice that the EmojiHubViewModel declaration is in the shared common code and can be used in both iOS and Android platforms.</p><pre>class EmojiHubViewModel(private val repository :EmojiHubRepository) : SharedViewModel() {<br><br>    ...<br><br>    init {<br>        sharedViewModelScope.launch {<br>            ...<br>        }<br>    }<br>}</pre><h4>ViewModel in the Android platform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*ebGEpcPLQ4mJitBkCoo0Ag.png" /><figcaption>SharedViewModel in the androidMain</figcaption></figure><pre>// shared/androidMain/.../viewModel/SharedViewModel<br>actual open class SharedViewModel: ViewModel() {<br><br>    actual val sharedViewModelScope: CoroutineScope = this.viewModelScope<br><br>    actual override fun onCleared() {<br>        super.onCleared()<br>    }<br>}</pre><p>The snippet code below shows how we use emojiHubViewModel in the EmojiHubScreen.</p><pre>@Composable<br>fun EmojiHubScreen() {<br><br>    val emojiHubViewModel: EmojiHubViewModel = koinViewModel()<br>    val items by emojiHubViewModel.items.collectAsState()<br><br>    Scaffold(topBar = {<br>        TopAppBar(title = {<br>            Text(text = &quot;EmojiHub&quot;)<br>        })<br>    }, content = { paddingValues -&gt;<br>        LazyColumn(modifier = Modifier.padding(paddingValues)) {<br>            items(items.size) { index -&gt;<br>                Item(items[index])<br>            }<br>        }<br>    })<br>}</pre><p>I’ll explain about fetching data using <a href="https://ktor.io/"><strong>ktor</strong></a> and dependency injection using <a href="https://insert-koin.io/"><strong>koin</strong></a> in the following in this article! So skip it for now!</p><h4>ViewModel in the iOS platform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*nH7PWtgR15uw9lDrvO3TXg.png" /><figcaption>SharedViewModel in the iosMain</figcaption></figure><pre>// shared/iosMain/.../viewModel/SharedViewModel<br>actual open class SharedViewModel {<br><br>    actual val sharedViewModelScope = MainScope()<br><br>    protected actual open fun onCleared() {}<br><br>    fun clear() {<br>        onCleared()<br>    }<br>}</pre><p>And this is how we use emojiHubViewModel in the ContentView.</p><pre>struct ContentView: View {<br><br> @StateObject<br> var emojiHubViewModel: EmojiHubViewModel()<br><br> var body: some View {<br>     Text(String(&quot;EmojiHub&quot;))<br>     List {<br>          ForEach(iOSEmojiHubViewModel.items, id: \.self) { item in<br>              Item(emojiItem: item)<br>          }<br>     }<br>  }<br>}</pre><h3>5. Networking</h3><p><a href="https://ktor.io/"><strong>Ktor</strong></a> is for anything from microservices to multiplatform HTTP client apps. To use it, add Ktor dependencies to your project in the build.gradle.kts as below.</p><pre>val koinVersion = &quot;3.4.3&quot;<br><br>// shared/build.gradle.kts<br>sourceSets {<br><br>      val commonMain by getting {<br>          dependencies {<br>              implementation(&quot;io.ktor:ktor-client-core:$ktorVersion&quot;)<br>              implementation(&quot;io.ktor:ktor-client-logging:$ktorVersion&quot;)<br>              implementation(&quot;io.ktor:ktor-client-content-negotiation:$ktorVersion&quot;)<br>          }<br>      }<br><br>     val androidMain by getting {<br>         dependsOn(commonMain)<br>         dependencies {<br>             ...<br>             implementation(&quot;io.ktor:ktor-client-okhttp:$ktorVersion&quot;)<br>         }<br>     }<br><br>     val iosMain by getting {<br>        dependsOn(commonMain)<br>        dependencies {<br>            implementation(&quot;io.ktor:ktor-client-darwin:$ktorVersion&quot;)<br>        }<br>     }<br>}</pre><p>Add the HttpClient file in the commonMain module as below:</p><pre>expect fun httpClient(config: HttpClientConfig&lt;*&gt;.() -&gt; Unit): HttpClient</pre><p>Declare httpClient with the actual keyword in the anroidMain:</p><pre>actual fun httpClient(config: HttpClientConfig&lt;*&gt;.() -&gt; Unit): HttpClient = HttpClient(OkHttp) {<br>    config()<br>}</pre><p>And httpClient with the actual keyword in the iosMain:</p><pre>actual fun httpClient(config: HttpClientConfig&lt;*&gt;.() -&gt; Unit): HttpClient = HttpClient(Darwin) {<br>    config()<br>}</pre><p>Now, use <strong>httpClient </strong>in EmojiHubRepository to fetch emojis from a remote server.</p><pre>class EmojiHubRepository(private val httpClient: HttpClient) {<br><br>    suspend fun getEmojis(): List&lt;EmojiItem&gt; {<br>        return try {<br>            httpClient.get(urlString = &quot;/api/all&quot;).body()<br>        } catch (e: Exception) {<br>            e.printStackTrace()<br>            emptyList()<br>        }<br>    }<br>}</pre><p>And in EmojiHubViewModel, use <strong>EmojiHubRepository</strong> to get data from remote or local sources<strong>.</strong></p><pre>class EmojiHubViewModel(private val repository :EmojiHubRepository) : SharedViewModel() {<br><br>    private val _items = MutableStateFlow&lt;List&lt;EmojiItem&gt;&gt;(listOf())<br><br>    @NativeCoroutinesState<br>    val items = _items.asStateFlow()<br><br>    init {<br>        sharedViewModelScope.launch {<br>            _items.update {<br>                repository.getEmojis() // get data through repository<br>            }<br>        }<br>    }<br>}</pre><h3>6. <em>Coroutines in Ios</em></h3><p>Add <a href="https://github.com/Kotlin/kotlinx.serialization"><strong>Kotlinx.Serialization</strong></a><strong> </strong>to your project.</p><blockquote>Kotlin serialization consists of a compiler plugin, that generates visitor code for serializable classes, a runtime library with core serialization API, and support libraries with various serialization formats.</blockquote><blockquote>- Supports Kotlin classes marked as @Serializable and standard collections.</blockquote><blockquote>- Provides <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/README.md#JSON">JSON</a>, <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/README.md#ProtoBuf">Protobuf</a>, <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/README.md#CBOR">CBOR</a>, <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/README.md#HOCON">Hocon</a>, and <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/README.md#properties">Properties</a> formats.</blockquote><blockquote>- Complete multiplatform support: JVM, JS, and Native.</blockquote><p><a href="https://github.com/Kotlin/kotlinx.serialization"><strong>Kotlinx.Serialization</strong></a> is used to serialize and deserialize objects of custom types.</p><pre>val kotlinxSerializationVersion = &quot;1.5.1&quot;<br><br>// shared/build.gradle.kts<br>sourceSets {<br><br>      val commonMain by getting {<br>          dependencies {<br>              implementation(&quot;org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlinxSerializationVersion&quot;)<br>              ...<br>          }<br>      }<br><br>     val androidMain by getting {<br>         dependsOn(commonMain)<br>         dependencies {<br>             ...<br>         }<br>     }<br><br>     val iosMain by getting {<br>        dependsOn(commonMain)<br>        dependencies {<br>            ...<br>        }<br>     }<br>}</pre><h4><strong>Reconfiguring httpClient</strong></h4><pre>// shared/commonMain/.../EmojiHubRepository<br>    class EmojiHubRepository {<br>        private val httpClient = httpClient {<br>            ...<br>            install(ContentNegotiation) {<br>                json(<br>                    Json {<br>                        ignoreUnknownKeys = true<br>                    }<br>                )<br>            }<br>        }<br>    }</pre><p>Get data from the server and then run the Android app.</p><pre>suspend fun getEmojis(): List&lt;EmojiItem&gt; {<br>        return try {<br>            httpClient.get(urlString = &quot;/api/all&quot;).body()<br>        } catch (e: Exception) {<br>            e.printStackTrace()<br>            emptyList()<br>        }<br>    }</pre><pre>class EmojiHubViewModel(private val repository :EmojiHubRepository) : SharedViewModel() {<br><br>    private val _items = MutableStateFlow&lt;List&lt;EmojiItem&gt;&gt;(listOf())<br><br>    @NativeCoroutinesState<br>    val items = _items.asStateFlow()<br><br>    init {<br>        sharedViewModelScope.launch {<br>            _items.update {<br>                repository.getEmojis()<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa6-tnXV6ZC_uV7txzXjJg.png" /></figure><h4>KMP-NativeCoroutines</h4><pre>// commonMain/viewModel/EmojiHubViewModel<br>class EmojiHubViewModel(private val repository :EmojiHubRepository) : SharedViewModel() {<br><br>    private val _items = MutableStateFlow&lt;List&lt;EmojiItem&gt;&gt;(listOf())<br><br>    @NativeCoroutinesState<br>    val items = _items.asStateFlow()<br><br>    ...<br>}</pre><p>IOSEmojiHubViewModel is in the iosApp module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*46PRZ6_WZk9LaqVNz1_POA.png" /></figure><p>In IOSEmojiHubViewModel, get data using KMPNativeCoroutinesAsync.</p><pre>@MainActor<br>class IOSEmojiHubViewModel: ObservableObject {<br><br>    private let githubViewModel = GithubViewModel()<br><br>    @Published<br>    var items = Array&lt;EmojiItem&gt;()<br><br>    var task: Task&lt;(), Never&gt;? = nil<br><br>    init() {<br>        task = Task {<br>            do {<br>                let asyncItems = asyncSequence(for: emojiHubViewModel.itemsFlow)<br>                for try await asyncItem in asyncItems {<br>                    items = asyncItem<br>                }<br>            } catch {<br>                print(&quot;Failed with error: \(error)&quot;)<br>            }<br>        }<br>    }<br><br>    func clear() {<br>        task?.cancel()<br>    }<br>}</pre><pre>struct ContentView: View {<br><br>    @StateObject<br>    var iOSEmojiHubViewModel = IOSEmojiHubViewModel()<br><br>    var body: some View {<br>        Text(String(&quot;EmojiHub&quot;))<br>        List {<br>            ForEach(iOSEmojiHubViewModel.items, id: \.self) { item in<br>                Item(emojiItem: item)<br>            }<br>        }<br>    }<br>}</pre><h3>7. Dependency Injection</h3><p>Add <a href="https://insert-koin.io/"><strong>Koin</strong></a> to your project for implementing a dependency injection pattern as below.</p><blockquote>💡<strong>Koin</strong> is a framework to help you build any kind of Kotlin &amp; Kotlin Multiplatform application, from Android mobile, and Multiplatform apps to backend <strong>Ktor</strong> server applications.</blockquote><pre>val koinVersion = &quot;3.4.3&quot;<br><br>// shared/build.gradle.kts<br>sourceSets {<br><br>      val commonMain by getting {<br>          dependencies {<br>             implementation(&quot;io.insert-koin:koin-core:$koinVersion&quot;)<br>             ...<br>          }<br>      }<br><br>     val androidMain by getting {<br>         dependsOn(commonMain)<br>         dependencies {<br>           implementation(&quot;io.insert-koin:koin-android:$koinVersion&quot;)<br>            ....<br>         }<br>     }<br><br>     val iosMain by getting {<br>        dependsOn(commonMain)<br>        dependencies {<br>            ...<br>        }<br>     }<br>}</pre><p>In EmojiHubRepository, inject HttpClient.</p><pre>class EmojiHubRepository(private val httpClient: HttpClient) {<br><br>    ...<br>}</pre><p>And in EmojiHubViewModel, inject EmojiHubRepository.</p><pre>// commonMain/viewModel/EmojiHubViewModel<br>class EmojiHubViewModel(private val repository :EmojiHubRepository) : SharedViewModel() {<br><br>    ...<br>}</pre><p>Declare a module to define dependencies as below:</p><pre>val appModule = module {<br>    single {<br>        httpClient {<br>           ...<br>        }<br>    }<br><br>    single {<br>        EmojiHubRepository(get())<br>    }<br><br>    sharedViewModel {<br>        EmojiHubViewModel(get())<br>    }<br>}</pre><p>Add start Koin in your project application class.</p><pre>//androidApp/MainApplication<br>class MainApplication : Application() {<br><br>    override fun onCreate() {<br>        super.onCreate()<br><br>        startKoin {<br>            androidContext(this@MainApplication)<br>            modules(appModule) // app modules<br>        }<br>    }<br>}</pre><p>And start Koin in the iosMain to use it.</p><pre>// shared/iosMain/.../KoinStarter.kt<br>fun startKoin() {<br>    startKoin { modules(appModule) }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*yXHUV3dLTutMue-yUtgC-g.png" /><figcaption>iOSApp.swift in iosApp module</figcaption></figure><p>Invoke startKoin in the iOSApp.</p><pre>@main<br> struct iOSApp: App {<br><br>     init() {<br>         KoinStarterKt.startKoin()<br>      }<br><br>      var body: some Scene {<br>         WindowGroup {<br>             ContentView()<br>         }<br>      }<br>}</pre><p>And GithubViewModelHelper is used to inject GithubViewModel in iOS.</p><pre>class EmojiHubViewModelHelper: KoinComponent {<br><br>    private val emojiHubViewModel: EmojiHubViewModel = get()<br><br>    @NativeCoroutinesState<br>    val items = emojiHubViewModel.items<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*46PRZ6_WZk9LaqVNz1_POA.png" /><figcaption>IOSEmojiHubViewModel in iosApp module</figcaption></figure><p>Now run the androidApp and iOSApp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa6-tnXV6ZC_uV7txzXjJg.png" /></figure><h3><strong>Libraries &amp; Tools</strong></h3><ul><li><a href="https://plugins.jetbrains.com/plugin/14936-kotlin-multiplatform">KMP plugin</a></li><li><a href="https://github.com/Kotlin/kdoctor">Kdoctor</a></li><li><a href="https://ktor.io/">Ktor</a></li><li><a href="https://github.com/Kotlin/kotlinx.serialization">Kotinx.Serialization</a></li><li><a href="https://github.com/rickclephas/KMP-NativeCoroutines">KMP-NativeCoroutines</a></li><li><a href="https://insert-koin.io/">Koin</a></li></ul><p>A simple sample project using KMP.</p><p><a href="https://github.com/ZahraHeydari/Kotlin-MultiPlatform-Mobile">https://github.com/ZahraHeydari/Kotlin-MultiPlatform-Mobile</a></p><p>Thank you for reading this story. Hope you find it helpful.</p><p>I’d really appreciate any feedback, please leave your comments below.</p><blockquote><em>You can find me on </em><a href="https://twitter.com/Zahra_HY"><em>Twitter</em></a><em> 🤓</em></blockquote><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4799fdfb69f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Pattern in Kotlin]]></title>
            <link>https://medium.com/@ZahraHeydari/singleton-pattern-in-kotlin-b09380c53b14?source=rss-a3bb29fe186------2</link>
            <guid isPermaLink="false">https://medium.com/p/b09380c53b14</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[singleton]]></category>
            <dc:creator><![CDATA[Zahra Heydari]]></dc:creator>
            <pubDate>Sat, 23 Sep 2023 13:24:51 GMT</pubDate>
            <atom:updated>2023-10-03T21:44:19.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqGVvXvRVaxYuwrmLDjQvg.jpeg" /></figure><p>First, let’s review what’s the Singleton pattern.</p><p>The singleton pattern is one of the creational design patterns that is used to limit the instances of a class to one. That means with the Singleton pattern, only one instance of a class exists in the whole project with global access.</p><blockquote><strong>Singleton</strong> is a creational design <strong>pattern</strong> that lets you ensure that a <strong>class</strong> has only one instance while providing a global <strong>access</strong> point to this instance.</blockquote><p>In Java:</p><pre>public class Singleton { // Thread safe and lazy.<br><br>    private static volatile Singleton sInstance; // Volatile is necessary<br><br>    private Singleton() {}<br><br>    public static Singleton getInstance() {<br>        if (sInstance == null) {<br>            synchronized (Singleton.class) { // synchronized to avoid concurrency problem<br>                if (sInstance == null) {<br>                    sInstance = new Singleton();<br>                }<br>            }<br>        }<br>        return sInstance;<br>    }<br>}</pre><blockquote><strong>Note:</strong> Prior knowledge of the <strong>Singleton pattern in Java</strong> is assumed as a foundation for comprehending its implementation in Kotlin. If you’re not already familiar with this pattern in Java, it’s advisable to first explore how to implement the Singleton pattern in that language. This will provide you with a solid understanding that will greatly facilitate your grasp of its Kotlin counterpart.</blockquote><h3>How to implement the Singleton pattern in Kotlin?</h3><p>Regular <strong>object</strong> class in Kotlin provides the Singleton behavior. It’s thread-safe and instantiated lazily when we access it for the first time.</p><h4>Thread safe and lazy:</h4><pre>object Singleton {<br>    // Code to be executed<br>}</pre><blockquote><strong>Note</strong>: You are not allowed to have any constructor inside the object class!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeEb37SdSs3DBTsIMFpoFg.png" /><figcaption>Under the hood of the Singleton object class</figcaption></figure><h3>How to make a class Singleton in Kotlin?</h3><p>For making a class Singleton, ensure that the class’s constructor is private. Declare the getInstance() function inside the companion object along with double-check locking and call the Volatile modifier on the instance property.</p><p>By marking the Singleton instance as volatile, you ensure that:</p><ul><li>Reads and writes to the instance are not reordered by the compiler or processor.</li><li>Changes made by one thread are visible to other threads immediately.</li></ul><h4>Double-Check Locking. Thread safe and lazy:</h4><pre>class Singleton private constructor() {<br><br>    companion object {<br><br>        @Volatile private var instance: Singleton? = null // Volatile modifier is necessary<br><br>        fun getInstance() =<br>            instance ?: synchronized(this) { // synchronized to avoid concurrency problem<br>                instance ?: Singleton().also { instance = it }<br>            }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgRYdc5rY0bdezWTy-9HPA.png" /><figcaption>Under the hood of the Singleton class (get instance by double-check locking)</figcaption></figure><h4>Simple, thread-safe, and lazy:</h4><pre>class Singleton private constructor() {<br><br>    companion object {<br>    <br>        val INSTANCE: Singleton by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { Singleton() }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnvrET9h-LPXreuWvdSIdg.png" /><figcaption>Under the hood of the Singleton class (get instance by lazy)</figcaption></figure><h4>But<strong> </strong>can we make a class Singleton by simply creating an instance of that on the top level?</h4><p>The answer is <strong>NO</strong>. Because the class’s constructor is private. That’s why it’s not possible to make an instance of the class outside its scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTTopE4ecKZTzBkGxR1LBQ.png" /></figure><h3>Advantages and Disadvantages of using Singleton Pattern</h3><h4>Advantages</h4><ol><li><strong>Reduce memory usage:</strong> By creating only one instance of a class, we can avoid allocating and deallocating memory for multiple objects of the same type. This can improve the cache efficiency and reduce the garbage collector overhead.</li><li><strong>Simplified access and control: </strong>Using a Singleton pattern can simplify the access and control of a shared resource. The only instance of the class can be accessed easily and the Singleton class can control the instantiation of the only instance and restrict the creation of multiple instances.</li></ol><h4>Disadvantages</h4><ol><li><strong>Reduced scalability and testability: </strong>By creating a global state, you can introduce dependencies and coupling between different components of your application, making it harder to modify or extend them. You can also limit the flexibility and configurability of your application, as you cannot easily replace or mock the singleton instance for different scenarios or environments.</li><li><strong>Increased complexity and risk: </strong>By implementing the singleton pattern, you have to deal with some technical challenges, such as ensuring thread safety, lazy initialization, serialization, and reflection. You also have to be careful about the design and implementation of your singleton class, as it can become a source of bugs, memory leaks, or performance bottlenecks if not done properly.</li></ol><p><a href="https://www.linkedin.com/advice/0/what-benefits-drawbacks-using-singleton-1e">What are the benefits and drawbacks of using the singleton pattern in performance-critical applications?</a></p><p><a href="https://gist.github.com/ZahraHeydari/1dd4f97b0a9f3b46af52697894046671">https://gist.github.com/ZahraHeydari/1dd4f97b0a9f3b46af52697894046671</a></p><p>Thank you for reading this story. Hope you find it helpful.</p><p>I’d really appreciate any and all feedback, please leave your comments below.</p><blockquote>You can find me on <a href="https://twitter.com/Zahra_HY">Twitter</a> <em>🤓</em></blockquote><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b09380c53b14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Overload a Function in Kotlin?]]></title>
            <link>https://medium.com/@ZahraHeydari/how-to-overload-a-function-in-kotlin-873bbf2038af?source=rss-a3bb29fe186------2</link>
            <guid isPermaLink="false">https://medium.com/p/873bbf2038af</guid>
            <category><![CDATA[default-arguments]]></category>
            <category><![CDATA[method-overloading]]></category>
            <category><![CDATA[overloading]]></category>
            <category><![CDATA[function-overloading]]></category>
            <category><![CDATA[kotlin-functions]]></category>
            <dc:creator><![CDATA[Zahra Heydari]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 10:32:50 GMT</pubDate>
            <atom:updated>2023-09-23T11:47:03.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chFli50b4C8jdfbWnOArvQ.jpeg" /></figure><p>First, let’s see what’s the function overloading and how we use it regularly.</p><p>In simple words, multiple functions with different signatures inside the same class are known as function overloading.</p><p>(A <strong>function signature</strong> consists of the function name, arguments type, and the number of arguments the function takes.)</p><p>A simple function overloading example:</p><pre>class Printer {<br><br>    fun print(number: Int) {<br>        // Code to be executed<br>    }<br><br>    fun print(text: String) {<br>        // Code to be executed<br>    }<br>}</pre><p>More examples:</p><pre>class Printer {<br><br>    fun print(number: Int) {<br>        // Code to be executed<br>    }<br><br>    fun print(number: Int, text: String) {<br>        // Code to be executed<br>    }<br><br>    fun print(number: Int, letter: Char, text: String) {<br>        // Code to be executed<br>    }<br>}</pre><pre>class Printer {<br><br>    fun print(list: List&lt;Int&gt;) {<br>        // Code to be executed<br>    }<br><br>    fun print(list: List&lt;String&gt;) {<br>        // Code to be executed<br>    }<br>}</pre><blockquote><strong>Note:</strong> The functions with the same names but different return types encounter a conflicting overloads compiler error.</blockquote><p>Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*Xq2OFanXcf-R7L2wNzIIuA.png" /></figure><pre>Conflicting overloads: public final fun print(): Int defined in Printer, public final fun print(): String defined in Printer.</pre><h3>But what happens if we only change the order of arguments?!</h3><pre>class Printer {<br><br>    fun print(number: Int, text: String) {<br>        // Code to be executed<br>    }<br><br>    fun print(text: String, number: Int) {<br>        // Code to be executed<br>    }<br>}</pre><p>As you see in the example above, the order of arguments can be changed and will not generate any error for overloading functions.</p><h3>Overloading private functions, possible?</h3><p>Yes. A private function can be overloaded since overloading functions are inside the same class.</p><pre>class Printer {<br><br>    private fun print(number: Int) {<br>        // Code to be executed<br>    }<br>     <br>    private fun print(number: Int, text: String) {<br>        // Code to be executed<br>    }<br>}</pre><h3>What about overloading static functions?</h3><p>The answer is yes. We can overload static functions but remember that the functions&#39; signatures must be different!</p><pre>object Printer {<br><br>    fun print(number: Int) {<br>        // Code to be executed<br>    }<br><br>    fun print(number: Int, text: String) {<br>        // Code to be executed<br>    }<br>}</pre><blockquote>Note: Function Overloading is compile time! It means it’s resolved during compile time as the compiler decides which function to call based on the number and types of arguments passed.</blockquote><p>Now return to the main question “How to overload a function in Kotlin”.</p><h3>How to overload a function in Kotlin?</h3><p>In Kotlin, default arguments allow us to specify a default value for a function parameter. This means that passing data into a function is optional for the default arguments. If the parameter is not explicitly passed in when the function is called, it will use the default value instead.</p><p>This becomes clear in the following example:</p><pre>fun main(args: Array&lt;String&gt;) {<br>    val printer = Printer()<br>    printer.print(number = 12) // Passing String value is optional here<br>}<br><br>class Printer {<br><br>    fun print(number: Int, text: String ?= &quot;Default text&quot;) {<br>        // Code to be executed<br>    }<br>}</pre><p>Kotlin function overloading feature empowers us with the ability to declare one function with different parameters and default arguments for operations that are logically related.</p><p>See the following example:</p><p><strong>Old style:</strong></p><pre>class Printer {<br><br>    fun print(number: Int) {<br>        // Code to be executed<br>    }<br><br>    fun print(text: String) {<br>        // Code to be executed<br>    }<br><br>    fun print(number: Int, text: String) {<br>        // Code to be executed<br>    }<br>}</pre><p><strong>In Kotlin:</strong></p><pre>fun main(args: Array&lt;String&gt;) {<br>    val printer = Printer()<br>    printer.print(number = 12)<br>    printer.print(text = &quot;Valid number!&quot;)<br>    printer.print(number = 12, &quot;Valid number!&quot;)<br>}<br><br>class Printer {<br><br>    fun print(number: Int? = 0, text: String? = &quot;Default text&quot;) { // Overloading feature<br>        // Code to be executed<br>    }<br>}</pre><p><strong>The benefits of function overloading:</strong></p><p>Function overloading enhances code <strong>readability</strong> by enabling programmers to use one function name for operations that are logically related.</p><p>It provides <strong>reusability</strong>. You don’t have to create new functions with different names for similar tasks. Instead, you can use the same function name and give it different types of information depending on the specific needs. It makes the code shorter and more adaptable. Moreover, it furnishes <strong>flexibility</strong> for managing diverse scenarios by accommodating a range of parameter combinations.</p><blockquote><em>You can find me on </em><a href="https://twitter.com/Zahra_HY"><em>Twitter</em></a><em> </em>🤓</blockquote><p><strong>Feedback is very welcome.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=873bbf2038af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>