<?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 Mustafa İçmen on Medium]]></title>
        <description><![CDATA[Stories by Mustafa İçmen on Medium]]></description>
        <link>https://medium.com/@musticmen?source=rss-a4080d72c487------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UoWorbgUYw-eb2WVILpgBA.jpeg</url>
            <title>Stories by Mustafa İçmen on Medium</title>
            <link>https://medium.com/@musticmen?source=rss-a4080d72c487------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 03:01:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@musticmen/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[MVP vs MVVM on Android]]></title>
            <link>https://medium.com/@musticmen/mvp-vs-mvvm-on-android-ddd4dd8c9a5b?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddd4dd8c9a5b</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 15:37:23 GMT</pubDate>
            <atom:updated>2022-04-18T15:37:23.611Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Model — View — Presenter (MVP) Pattern</h3><ul><li><strong>Model:</strong> Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.</li><li><strong>View:</strong> UI(User Interface) layer. It provides the visualization of the data and keep a track of the user’s action in order to notify the Presenter.</li><li><strong>Presenter:</strong> Fetch the data from the model and applies the UI logic to decide what to display. It manages the state of the View and takes actions according to the user’s input notification from the View.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*7UxcJ-RL2yWETzBh7rq4Aw.png" /></figure><p>Presenter and View are implemented from their interfaces. Presenter is the manager between Model and View, uses them over interfaces. Here is sample implementation: (<a href="https://github.com/cimenmus/mvp-sample">https://github.com/cimenmus/mvp-sample</a>)</p><pre>interface AdContract {</pre><pre>    interface View {<br>        fun showLoading()<br>        fun hideLoading()<br>        fun showAd(ad: AdModel)<br>        fun initViews()<br>    }</pre><pre>    interface Presenter {<br>        fun initLogic()<br>        fun getAdDetails()<br>    }<br>}</pre><pre>//********************************************</pre><pre>class AdPresenter(private val view: AdContract.View) : AdContract.Presenter {</pre><pre>    private val adRepository = AdRepository()</pre><pre>    override fun initLogic() {<br>        view.initViews()<br>        getAdDetails()<br>    }</pre><pre>    override fun getAdDetails() {<br>        GlobalScope.<em>launch </em><strong>{<br>            </strong>view.showLoading()<br>            val ad = adRepository.getAdDetails()<br>            withContext(Dispatchers.Main) <strong>{<br>                </strong>view.showAd(ad)<br>                view.hideLoading()<br>            <strong>}<br>        }<br>    </strong>}<br>}</pre><pre>//********************************************</pre><pre>class AdActivity : AppCompatActivity(), AdContract.View {</pre><pre>    private lateinit var binding: ActivityAdBinding<br>    private lateinit var adPresenter: AdContract.Presenter</pre><pre>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        binding = ActivityAdBinding.inflate(<em>layoutInflater</em>)<br>        setContentView(binding.<em>root</em>)<br>        adPresenter = AdPresenter(view = this)<br>        adPresenter.initLogic()<br>    }</pre><pre>    override fun initViews() {<br>        binding.swipeRefreshLayout.setOnRefreshListener <strong>{<br>            </strong>adPresenter.getAdDetails()<br>        <strong>}<br>    </strong>}</pre><pre>    override fun showLoading() {<br>        binding.swipeRefreshLayout.<em>isRefreshing </em>= true<br>    }</pre><pre>    override fun hideLoading() {<br>        binding.swipeRefreshLayout.<em>isRefreshing </em>= false<br>    }</pre><pre>    override fun showAd(ad: AdModel) {<br>        binding.adInfoTextView.<em>text </em>= ad.toString()<br>    }<br>}</pre><h3>The Model — View — ViewModel (MVVM) Pattern</h3><p>MVVM pattern has some similarities with the MVP(Model — View — Presenter) design pattern as the <strong>Presenter</strong> role is played by the <strong>ViewModel</strong>. However, the drawbacks of the MVP pattern has been solved by MVVM. It suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. The separate code layers of MVVM are:</p><ul><li><strong>Model:</strong> This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data.</li><li><strong>View:</strong> The purpose of this layer is to inform the ViewModel about the user’s action. This layer observes the ViewModel and does not contain any kind of application logic.</li><li><strong>ViewModel:</strong> It exposes those data streams which are relevant to the View. Moreover, it servers as a link between the Model and the View.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*bPLQtGt4IHxai17-ikCFrw.png" /></figure><h3>Difference Between MVP and MVVM Design Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTyvbh56OxfHeLm8eLXPOA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIfoBLrKd44gwcErNSNpDA.png" /></figure><p>Sources</p><ul><li><a href="https://www.geeksforgeeks.org/difference-between-mvp-and-mvvm-architecture-pattern-in-android/">Difference Between MVP and MVVM Architecture Pattern in Android - GeeksforGeeks</a></li><li><a href="https://github.com/cimenmus/mvp-sample">GitHub - cimenmus/mvp-sample</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddd4dd8c9a5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatsheet — Small Questions]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatsheet-small-questions-df29dbbc34c?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/df29dbbc34c</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 15:04:11 GMT</pubDate>
            <atom:updated>2022-04-17T15:04:11.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Cheatsheet — Small Questions</h3><h4>May you use IntArray and an Array&lt;Int&gt; is in Kotlin interchangeably?</h4><p>No, Array&lt;Int&gt; is an Integer[] under the hood, while IntArray is an int[].</p><h4>What is the difference between open and public in Kotlin?</h4><ul><li>If you do not specify any visibility modifier, public is used by default, which means that your declarations will be visible everywhere. public is the default if nothing else is specified explicitly.</li><li>The open keyword means “open for extension“. The open annotation on a class is the opposite of Java’s final: <em>it allows others to inherit from this class</em>.</li><li>Kotlin classes and class methods of a kotlin class could are final by default. That means a class can not be extended and a method of it can not be overriden by default. To make them extendable/overridable, we need to add open keyword.</li></ul><pre>class EventManager {<br>    fun sendLog() {<br>        <em>println</em>(&quot;log is send&quot;)<br>    }<br>}</pre><pre>// error because EventManager and sendLog() are final<br>class FirebaseEventManager : EventManager() {<br>    override fun sendLog() {<br>        <em>println</em>(&quot;Firebase log sent&quot;)<br>    }<br>}</pre><pre>// ------------------------</pre><pre>open class EventManager {<br>    open fun sendLog() {<br>        <em>println</em>(&quot;log is send&quot;)<br>    }<br>}<br><br>class FirebaseEventManager : EventManager() {<br>    override fun sendLog() {<br>        <em>println</em>(&quot;Firebase log sent&quot;)<br>    }<br>}</pre><h4>What is the difference between * and Any in Kotlin generics?</h4><ul><li>When we define a collection with *, it should contain the object of only that type. There should not be any mix and match between the data types inside a collection.</li></ul><pre>class ArrayUtil {<br>    fun findElement(array: Array&lt;*&gt;, element: Int) {<br>        for (i in array.<em>indices</em>) {<br>            if (array[i] == element) {<br>                <em>println</em>(&quot;Element found at $i&quot;)<br>            }<br>        }<br>    }<br>}<br><br>fun main() {<br>    val num = <em>arrayOf</em>(1, 2, 3, 4)<br>    ArrayUtil().findElement(num, 2)<br>}<br>// element found at 1</pre><ul><li>If we use Any, we can mix and match the data types, which means we can have multiple data types in a collection.</li></ul><pre>class Example&lt;Any&gt;(input: Any?) {<br>    init {<br>        <em>println</em>(&quot;I am getting called with the value $input&quot;)<br>    }<br>}<br><br>fun main() {<br>    var instance1 = Example(&quot;JAVA&quot;)<br>    var instance2 = Example(10)<br>}<br>// I am getting called with the value JAVA<br>// I am getting called with the value 10</pre><h4>What is the use of @JvmStatic, @JvmOverloads, and @JvmFiled in Kotlin?</h4><ul><li><strong>@JvmStatic:</strong> The @JvmStatic annotation is used to tell the compiler that the method is a static method, and you can use it in Java code. (<a href="https://medium.com/@musticmen/kotlin-cheatsheet-9-companion-object-47815b8001f1">https://medium.com/@musticmen/kotlin-cheatsheet-9-companion-object-47815b8001f1</a>)</li><li><strong>@JvmField:</strong> The @JvmField annotation is used to access the fields of a Kotlin class from Java code without any getters and setters. We need to use the @JvmField in the Kotlin code.</li><li><strong>@JvmOverloads:</strong> The @JvmOverloads annotation is required when we need to use the default values passed as an argument in Kotlin code from the Java code.</li></ul><h4>What is the difference between == operator and === operator in Kotlin?</h4><p>The == operator is generally used to compare the values stored in variables, and the === operator is used to check if the reference of the variables are equal or not.</p><p>In the case of primitive types, the === operator is also used to check for the value and not reference.</p><pre>data class User(private val name: String)</pre><pre>// wrapper example<br>val user1 = User(&quot;murat&quot;)<br>val user2 = User(&quot;murat&quot;)<br><em>println</em>(user1 == user2) // true<br><em>println</em>(user1 === user2) // false<br><br>// primitive example<br>val int1 = 10<br>val int2 = 10<br><em>println</em>(int1 == int2) // true<br><em>println</em>(int1 === int2) // true</pre><h3>Sources</h3><ul><li><a href="https://www.fullstack.cafe/blog/kotlin-interview-questions">40 Kotlin Interview Questions Android Devs Must Know | FullStack.Cafe</a></li><li><a href="https://www.fullstack.cafe/blog/kotlin-interview-questions">40 Kotlin Interview Questions Android Devs Must Know | FullStack.Cafe</a></li></ul><p><a href="https://www.tutorialspoint.com/difference-between-and-any-in-kotlin-generics#:~:text=When%20we%20define%20a%20collection,data%20types%20in%20a%20collection">https://www.tutorialspoint.com/difference-between-and-any-in-kotlin-generics#:~:text=When%20we%20define%20a%20collection,data%20types%20in%20a%20collection</a>.</p><p><a href="https://www.javatpoint.com/kotlin-interview-questions">Kotlin Interview Questions (2022) - javatpoint</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df29dbbc34c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatsheet 9 — Companion Object]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatsheet-9-companion-object-47815b8001f1?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/47815b8001f1</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 12:57:23 GMT</pubDate>
            <atom:updated>2022-04-17T14:47:20.634Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Cheatsheet 9 — Companion Object</h3><p>Unlike Java or C#, Kotlin doesn’t have static members or member functions. If you need to write a function that can be called without having a class instance but needs access to the internals of a class, you can write it as a member of a companion object declaration inside that class.</p><pre>class EventManager {<br>    companion object {<br>        const val name = &quot;FirebaseEventManager&quot;<br>    }<br>}<br><br>val <em>manager1 </em>= EventManager.Companion.name<br>val <em>manager2 </em>= EventManager.name // short version of above line</pre><p>Companion object has its class name too:</p><pre>class EventManager {<br>    companion object FirebaseManager{<br>        val name = &quot;FirebaseManager&quot;<br>    }<br>}<br><br>val <em>manager1 </em>= EventManager.FirebaseManager.name<br>val <em>manager2 </em>= EventManager.name // short version of above line</pre><h3>@JvmStatic</h3><p>Changes the strategy to converting Kotlin code to Java code. It makes easier to calling our companion object method/property from Java code. Simply, this annotation tells the Kotlin compiler to generate <strong>one additional static method</strong> for the annotated function under the hood.</p><h4>Behind the scenes without @JvmStatic</h4><p><strong>Kotlin code</strong></p><pre>class Plant {<br>    companion object {<br>        fun waterAll() { }<br>    }<br>}</pre><p><strong>Decompiled Java code</strong></p><pre>public final class Plant {</pre><pre>   public static final Plant.Companion Companion = <br>       new Plant.Companion();</pre><pre>   public static final class Companion {<br>       public final void waterAll() { }<br>       private Companion() { }<br>   }<br>}</pre><p>We have to call our companion object function from java like that:</p><pre>Plant.Companion.waterAll();</pre><h4>Behind the scenes with @JvmStatic</h4><p><strong>Kotlin code</strong></p><pre>class Plant {<br>    companion object {<br>        @JvmStatic<br>        fun waterAll() { }<br>    }<br>}</pre><p><strong>Decompiled Java code</strong></p><pre>public final class Plant {</pre><pre>   public static final Plant.Companion Companion = <br>       new Plant.Companion();</pre><pre>   @JvmStatic<br>   public static final void waterAll() { Companion.waterAll();}</pre><pre>   public static final class Companion {<br>      @JvmStatic<br>      public final void waterAll() { }<br>      private Companion() { }<br>   }<br>}</pre><p>We can call our companion object function from java as static too:</p><pre>Plant.waterAll();<br>Plant.Companion.waterAll();</pre><p>When to use</p><ul><li>The most important use case for this annotation is, of course, better Java interoperability. When you know that your Kotlin code won’t be used in Java, you don’t have to worry about adding the @JvmStatic annotation. This keeps your code cleaner. However, if your Kotlin code is called from Java, it makes sense to add the annotation. This will prevent your Java code from polluting with the name Companion everywhere.</li><li>With this method, it’s easier to integrate with some Java frameworks such as JUnit (Unit tests). It’s also easier and more idiomatic to call such methods from Java.</li><li>There is no performance gain or loss in terms of memory allocation.</li></ul><h3>@JvmField</h3><p>The @JvmField annotation is used to access the fields of a Kotlin class from Java code without any getters and setters. We need to use the @JvmField in the Kotlin code.</p><h3>@JvmOverloads</h3><p>The @JvmOverloads annotation is required when we need to use the default values passed as an argument in Kotlin code from the Java code.</p><p>Sources</p><ul><li><a href="https://stackoverflow.com/questions/48780003/why-and-when-to-use-jvmstatic-with-companion-objects">Why and when to use @JvmStatic with companion objects?</a></li><li><a href="https://www.javatpoint.com/kotlin-interview-questions">Kotlin Interview Questions (2022) - javatpoint</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47815b8001f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatsheet — const vs val]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatsheet-const-vs-val-d48aa7f72be3?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/d48aa7f72be3</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 12:25:52 GMT</pubDate>
            <atom:updated>2022-04-17T12:25:52.556Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Cheatsheet — const vs val</h3><pre>val MY_CONSTANT_1 = &quot;Constants1&quot;<br>// or <br>const val MY_CONSTANT_2 = &quot;Constants2&quot;</pre><p>Both val and const are immutable.const is used to declare compile-time constants, whereas val for run-time constants.</p><pre>// Assignment done at compile-time<br>const val VENDOR_NAME = &quot;Kifayat Pashteen&quot;<br><br>val ip = getIP()  // Assignment done at run-time<br>cons val ip = getIP()  // error</pre><p>There are some restrictions for const:</p><ol><li>Must be at the top level or a member of an object or a companion object.</li><li>Should start from a primitive data-type</li><li>No custom getter So, you can’t assign a const variable to a function or a class because the variable will be initialized at runtime rather than compile-time.</li></ol><p>Sources</p><ul><li><a href="https://stackoverflow.com/questions/37595936/what-is-the-difference-between-const-and-val">What is the difference between &quot;const&quot; and &quot;val&quot;?</a></li><li><a href="https://www.geeksforgeeks.org/whats-the-difference-between-const-and-val-in-kotlin/">What&#39;s the Difference Between &quot;const&quot; and &quot;val&quot; in Kotlin? - GeeksforGeeks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d48aa7f72be3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatsheet — Creating class instances]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatsheet-creating-class-instances-6806eabd8680?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/6806eabd8680</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 11:55:28 GMT</pubDate>
            <atom:updated>2022-04-17T11:56:15.562Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Cheatsheet — Creating class instances</h3><ul><li>Primary constructor can be defined while class is declaring</li></ul><pre>class User {<br>    var name: String = &quot;&quot;<br>    constructor(name: String) {<br>        this.name = name<br>    }<br>}</pre><pre>class User(var name: String) // the same as above</pre><pre>val user = User(name = &quot;murat&quot;)<br>val user2 = User() // error</pre><ul><li>Constructor parameters must use var or val when they are used as a property of the class. They do not need to be properties if they are only used for class initialization.In the example below, the parameter must be a property (var or val) because it is used in a method:</li></ul><pre>class User(var name: String, age: Int) {<br><br>    val hasName = name.<em>isNotEmpty</em>()<br><br>    init {<br>        <em>println</em>(&quot;age: $age&quot;)<br>       // age can be used only constructors and initializers because it is not a property of the class</pre><pre>    }<br><br>    fun info() = name<br>    fun info() = &quot;$name $age&quot; // error because age is not property<br>}</pre><pre>val user = User(name = &quot;murat&quot;, age = 32)<br>println(&quot;name: ${user.name}&quot;)<br>println(&quot;age: ${user.age}&quot;) // error, because age is not property of User</pre><ul><li>If primary constructor is defined, other constructors have to call it.</li></ul><pre>class User(var name: String) {<br>    var age: Int = 0<br>    constructor(name: String, age: Int) : this(name) {<br>        this.age = age<br>    }<br>}</pre><pre>val user1 = User(name = &quot;murat&quot;)<br>val user2 = User(name = &quot;murat&quot;, age = 32)</pre><ul><li>Other constructors can not declare property for a class, even if primary constructor available or not.</li></ul><pre>class User(var name: String) {<br>    <br>    // compile time error because of declaring age as var<br>    constructor(name: String, var age: Int): this(name) {<br>        <em>println</em>(&quot;$name is $age years old&quot;)<br>    }<br><br>    constructor(name: String, age: Int): this(name) {<br>        <em>println</em>(&quot;$name is $age years old&quot;)<br>    }<br>}</pre><pre>val user1 = User(name = &quot;murat&quot;)<br><em>println</em>(&quot;User 1 name: ${user1.name}&quot;)<br><em>println</em>(&quot;User 1 age: ${user1.age}&quot;) // error<br><br>val user2 = User(name = &quot;mustafa&quot;, age = 30)<br><em>println</em>(&quot;User 2 name: ${user2.name}&quot;)<br><em>println</em>(&quot;User 2 age: ${user2.age}&quot;) // error</pre><ul><li>init{} block is body of the primary constructor. So it is called before the other constructors. Even if there is no primary constructor, init{} is called first, because kotlin has default empty constructor like Java. So it is like our primary constructor in that situation.</li></ul><pre>class User(var name: String) {<br><br>    init {<br>        <em>println</em>(&quot;$name is initialized&quot;)<br>    }<br><br>    constructor(name: String, age: Int) : this(name) {<br>        <em>println</em>(&quot;$name is $age years old&quot;)<br>    }<br><br>    constructor(name: String, birthDate: String) : this(name) {<br>        <em>println</em>(&quot;$name is born at $birthDate&quot;)<br>    }<br>}</pre><pre>val user1 = User(name = &quot;murat&quot;)<br>val user2 = User(name = &quot;musa&quot;, age = 30)<br>val user3 = User(name = &quot;mustafa&quot;, birthDate = &quot;04.11.1991&quot;)</pre><pre>// murat is initialized<br>// musa is initialized<br>// musa is 30 years old<br>// mustafa is initialized<br>// mustafa is born at 04.11.1991</pre><p>Sources</p><p><a href="https://stackoverflow.com/questions/45821929/in-which-situation-val-var-is-necessary-in-kotlin-constructor-parameter">In which situation val/var is necessary in Kotlin constructor parameter?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6806eabd8680" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatsheet 8 — lazy vs lateini]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatsheet-8-lazy-vs-lateini-ea2600f5e6c0?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea2600f5e6c0</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:57:21 GMT</pubDate>
            <atom:updated>2022-04-17T13:07:43.165Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Cheatsheet — lazy vs lateinit</h3><pre>private val name1: String by <em>lazy </em><strong>{ </strong>&quot;murat&quot; <strong>}</strong></pre><pre>private lateinit var name2: String<br>//...<br>name2 = &quot;mustafa&quot;</pre><ul><li>in lateinit , developer has to initialize it, but in lazy, it will be initialized by compiler when it is needed.</li><li>We can not have a custom getter to lateinit property</li><li>By default, the lazy property is synchronised or <strong>thread-safe</strong>. That means only a single thread will compute its value and all threads will use the same value. But there is an overload to the lazy function where we can pass the LazyThreadSafetyMode also.</li><li>We can do other computations also before initializing the actual property in the same lazy function.</li><li>lazy can be used only val , that means it is immutable. lateinit can be used only var , that means it it mutable</li></ul><pre>private val name1: String by <em>lazy </em><strong>{ </strong>&quot;murat&quot; <strong>}<br></strong>private var name1: String by <em>lazy </em><strong>{ </strong>&quot;murat&quot; <strong>} // error</strong></pre><pre>private lateinit var name2: String<strong><br></strong>private lateinit val name2: String <strong>// error</strong></pre><ul><li>lazy variable can be defined as nullable, butlateinit can not.</li></ul><pre>private val name1: String by <em>lazy </em><strong>{ </strong>&quot;murat&quot; <strong>}<br></strong>private var name1: String? by <em>lazy </em><strong>{ </strong>&quot;murat&quot; <strong>}</strong></pre><pre>private lateinit var name2: String<strong><br></strong>private lateinit val name2: String? <strong>// error</strong></pre><ul><li>lazy can be used for primitive types, butlateinit can not.</li></ul><pre>private val age1: Int by <em>lazy </em><strong>{ </strong>8<strong> }<br><br></strong>private lateinit val age2: Int <strong>// error</strong></pre><ul><li>lazy can only be initialized from the initializer lambda, butlateinit can be initialized everywhere.</li><li>lazy can be initialized single time, butlateinit can be initialized multiple times.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OarG1quYBLY5ecj1MWy6w.png" /></figure><p><strong>When to use lazy</strong>:</p><ol><li>That object/property/variable is dependent on another object to initialise first and use its reference.</li><li>The flow is such that we need that object only in a certain condition.</li></ol><p>Sources</p><p><a href="https://agrawalsuneet.github.io/blogs/lazy-property-in-kotlin/#:~:text=*%20To%20create%20an%20instance%20of,use%20the%20%5Blazy%5D%20function.&amp;text=*%20Gets%20the%20lazily%20initialized%20value,lifetime%20of%20this%20Lazy%20instance">https://agrawalsuneet.github.io/blogs/lazy-property-in-kotlin/#:~:text=*%20To%20create%20an%20instance%20of,use%20the%20%5Blazy%5D%20function.&amp;text=*%20Gets%20the%20lazily%20initialized%20value,lifetime%20of%20this%20Lazy%20instance</a>.</p><p><a href="https://www.baeldung.com/kotlin/lazy-initialization">https://www.baeldung.com/kotlin/lazy-initialization</a></p><p><a href="https://stackoverflow.com/questions/36623177/property-initialization-using-by-lazy-vs-lateinit">Property initialization using &quot;by lazy&quot; vs. &quot;lateinit&quot;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea2600f5e6c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatseet — data clas]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatseet-data-clas-f715623ccf43?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/f715623ccf43</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 10:55:40 GMT</pubDate>
            <atom:updated>2022-04-17T14:39:38.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Cheatsheet — data class</h3><pre>val : adventureBook = Book(&quot;Harry Potter &quot;, &quot;j. k. rowling&quot;, 700)</pre><p>Main purpose is holding data</p><ul><li>getter(), setter() , equals() , hashCode() , toString() ,copy() and componentN() functions defined automatically</li><li>Primary constructor is required</li><li>Needs at least one parameter in its primary constructor</li><li>Every parameter in primary constructor has to be defined as var or val</li><li>Data classes cannot be abstract, open, sealed or inner . That meas data classes can not be extended.</li></ul><p><strong>copy()</strong></p><pre>val adventureBook = Book(&quot;Harry Potter &quot;, &quot;j. k. rowling&quot;, 700)<br>val fantasticBook2 = adventureBook.copy() // full copy<br>val fantasticBook3 = adventureBook.copy(page = 650)</pre><p><strong>componentN()</strong></p><pre>adventureBook.component1() // name<br>adventureBook.component2() //author<br>adventureBook.component3() //page</pre><p><strong>How to override default getter of a data class?</strong></p><p>The problem with this approach is that <a href="https://kotlinlang.org/docs/reference/data-classes.html">data classes</a> aren’t really meant for altering data like this. They are really just for holding data. Overriding the getter for a data class like this would mean that Test(0) and Test(-1) wouldn&#39;t equal one another and would have different hashCodes, but when you called .value, they would have the same result. This is inconsistent, and while it may work for you, other people on your team who see this is a data class, may accidentally misuse it without realizing how you&#39;ve altered it / made it not work as expected (i.e. this approach wouldn&#39;t work correctly in a Map or a Set).</p><p>Approach 1:</p><pre>data class User(private val _age: Int) {<br>    val age: Int<br>        get() = if (_age &lt; 0) 0 else _age<br>}<br></pre><p>That will works as expected, e.i it has <strong>one</strong> field, one getter, right equals, hashcode and component1. The catch is that toString and copy are weird:</p><pre>println(User(1))          // prints: User(_value=1)<br>User(1).copy(_age = 5)  // &lt;- weird naming</pre><p>To fix the problem with toString you may redefine it by hands. I know of no way to fix the parameter naming but not to use data at all.</p><p>Approach 2:</p><pre>data class User(private val _age: Int) {<br>    val age = _age<br>        get(): Int {<br>            return if (field<strong> </strong>&lt; 0) 0 else field<strong><br>        </strong>}<br>}</pre><p>Good approach (Better but why?)</p><pre>data class User(val age: Int) {<br>    val safeAge: Int<br>        get() = if (age &lt; 0) 0 else age<br>}</pre><p>Sources</p><ul><li><a href="https://medium.com/@busetekinaydin/kotlin-%C3%B6%C4%9Freniyorum-companion-object-ve-data-class-part-3-852df0da0409">Kotlin Öğreniyorum, Companion Object ve Data Class — Part 3</a></li><li><a href="https://www.fullstack.cafe/blog/kotlin-interview-questions">40 Kotlin Interview Questions Android Devs Must Know | FullStack.Cafe</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f715623ccf43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatsheet 7 — Flows vs LiveData]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatsheet-7-flows-vs-livedata-39c246f60ab1?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/39c246f60ab1</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 12:58:08 GMT</pubDate>
            <atom:updated>2022-04-16T14:58:10.352Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Cheatsheet 7 — Flows vs LiveData</h3><p>The new approach on Android Development is migration from LiveData to StateFlow . Here is the reasons:</p><ul><li>LiveData is not built on top of Coroutines and Kotlin. So our module has to be Android Module, but using flow we can set our module as Kotlin Module. In Clean Architecture terms, while LiveData works fine for the Presentation Layer, it does not fit well in the Domain Layer, which should ideally be platform-independent (meaning a pure Kotlin/Java module); and it does not fit very well in the Data Layer either (Repositories implementations and Data Sources), as we usually should offload data access work to worker threads.</li><li>Threading: LiveData is closely bound to UI (no natural way to offload work to worker threads). Threading issue especially when used in Repositories. And we decide to use setValue() or postValue() methods to set value of LiveData according to the thread.</li><li>LiveData is a structure that is readable and writable only on the main thread. Even if we can post value from the main thread, LiveData’s value will be updated from the main thread internally. This means that we will often change threads (worker thread → main thread) when we want to update the LiveData object.</li><li>The same situation will happen with the reading value of the LiveData object. If we check the observe method’s internal implementation, we can see that this method can be used only from the main thread.</li><li>Lots of Boiler Plate Codes especially while using transformations. Because we use Flow ,RxJava or coroutineson Data and Domain, but we use LiveData on UI.</li><li>Lack of seamless data integration across between database and UI especially using Room.</li><li>Writing Unit tests is easier for Flow than LiveData</li></ul><p><strong>Migrating to StateFlow</strong></p><pre>// viewModel<br>private val _stateFlow = <em>MutableStateFlow</em>(&quot;Hello World&quot;)<br>val stateFlow: StateFlow&lt;String&gt; = _stateFlow.<em>asStateFlow</em>()</pre><pre>fun triggerStateFlow() {<br>    _stateFlow.value = &quot;StateFlow&quot;<br>}</pre><pre><em>// activity/fragment/view<br>lifecycleScope</em>.<strong>launchWhenResumed</strong> <strong>{<br>    </strong>viewModel.stateFlow.collectLatest <strong>{<br>        </strong>binding.stateFlowTextView.<em>text </em>= <strong>it<br>    }<br>}</strong></pre><p>There are two things to do:</p><ul><li>LiveData is lifecycle aware, but StateFlow <strong>is not</strong>. Bu sebeple StateFlow observe edilirken XXscope.launch yerine<a href="https://developer.android.com/reference/kotlin/androidx/lifecycle/LifecycleCoroutineScope">LifecycleCoroutineScope</a> extension’ları olan launch yerinelaunchWhenStarted, launchWhenResumed ya da launchWhenCreatedile kullanılmalı. hot flow’lar da collector/consumer’ı olmasa da emit etmeye devam ettiği için, launch ile kullanırsak bağlı olduğu scope sonlandırılınca kendisi hala dinlemeye devam eder.</li><li><strong>StateFlow </strong>is conflated<strong>, </strong>it means that <strong>only the most recently sent value will be collected by subscribers, and if the new value is equal to the last emitted value, it will not be emitted again</strong>. The equality is implemented by the <strong>Any.equals</strong> contract.</li></ul><p><strong>Combine multiple sources: MediatorLiveData -&gt; Flow.combine</strong></p><p>MediatorLiveData allows you to observe the changes of one or more data sources and perform corresponding operations based on the new data obtained. The value of MediatorLiveData can usually be updated in the following way:</p><pre>val liveData1: LiveData&lt;Int&gt; = ...<br>val liveData2: LiveData&lt;Int&gt; = ...</pre><pre>val result = MediatorLiveData&lt;Int&gt;()</pre><pre>result.addSource(liveData1) { value -&gt;<br>    result.setValue(liveData1.value ?: 0 + (liveData2.value ?: 0))<br>}<br>result.addSource(liveData2) { value -&gt;<br>    result.setValue(liveData1.value ?: 0 + (liveData2.value ?: 0))<br>}</pre><p>The same function is more straightforward to operate using Kotlin data flow:</p><pre>val flow1: Flow&lt;Int&gt; = ...<br>val flow2: Flow&lt;Int&gt; = ...</pre><pre>val result = combine(flow1, flow2) { a, b -&gt; a + b }</pre><p><a href="https://link.segmentfault.com/?enc=iEGrRpF2ojAm07YP9015Gg%3D%3D.LwtPqJmVAuSMgvd8B9F3oHJDTcFuSEC%2FRhQ0MUsvdCOitfoH%2BwNz21p4MnnR3NzGpdqmb8yB5j73pd19gbY45VAI%2BGd0eLe6tCCFoWZrMhbG3xUZvigF47iiwE%2BJHVwK3VyNckG6x%2Fwa%2Bd%2FrgVHY4ZOFT52Ti6uwLKpohrViJYQ%3D">combineTransform </a>or <a href="https://link.segmentfault.com/?enc=QNhl8qk1sskGtFRy9R83IA%3D%3D.5GYsH4qWSaEMZdKosBVU0B9a%2BppSmDgO%2FIiJMmsLh5rgXimChvcjF7VP4a48uwWaQFh1aF9s8weZs8uSXlF5WKx90cunMpSlbSEoVH0GmiHAXpEKXvJsBJzwM5XaBcWeEayWog9cuW0rh23vYDD9NQ%3D%3D">zip </a>function can also be used here.</p><p>Sources</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6Jc6-INantQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6Jc6-INantQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6Jc6-INantQ%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f47cefd99940a05203ea443215fdee/href">https://medium.com/media/52f47cefd99940a05203ea443215fdee/href</a></iframe><ul><li><a href="https://github.com/cimenmus/flows_vs_live_data">GitHub - cimenmus/flows_vs_live_data</a></li><li><a href="https://logidots.com/insights/live-data-flow-shared-flow-state-flow-2/#:~:text=StateFlow(hot%20stream)%20does%20similar,with%20power%20of%20flow&#39;s%20api.">Live data, Flow, Shared flow &amp; State flow - Logidots</a></li><li><a href="https://medium.com/swlh/migrating-from-livedata-to-stateflow-4f28d6889a04">Migrating From LiveData to StateFlow</a></li><li><a href="https://proandroiddev.com/should-we-choose-kotlins-stateflow-or-sharedflow-to-substitute-for-android-s-livedata-2d69f2bd6fa5">Substituting Android&#39;s LiveData: StateFlow or SharedFlow?</a></li></ul><p><a href="https://segmentfault.com/a/1190000040256135/en">https://segmentfault.com/a/1190000040256135/en</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39c246f60ab1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatsheet 6 — Flows]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatsheet-6-flows-50906c521d17?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/50906c521d17</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Sat, 16 Apr 2022 12:33:27 GMT</pubDate>
            <atom:updated>2022-04-16T14:55:49.172Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Cheatsheet 6 — Flows</h3><p>Flows are alternative for Observable/Flowable of RxJava.</p><pre>// Flow way<br>val myIntFlow: Flow&lt;Int&gt; = flow { emit(1)}<br>myIntFlow.collect { println(it) }</pre><pre>// RxJava way<br>val myIntStream: Observer&lt;Int&gt; = Observable.create { it.emit(1) }<br>myInteStream.subscribe {.println(it) }</pre><p>Normal flow’un sadece bir collector’u olabilir(çünkü create edip observe ediyoruz).</p><pre>//viewModel<br>fun triggerFlow(): Flow&lt;String&gt; = <em>flow </em><strong>{<br>    </strong><em>repeat</em>(times = 5) <strong>{<br>        </strong>emit(value = &quot;Item $<strong>it</strong>&quot;)<br>        delay(1000L)<br>    <strong>}<br>}</strong></pre><pre><em>// activity/fragment/view<br>lifecycleScope</em>.<em>launch </em><strong>{<br>    </strong>viewModel.triggerFlow().collectLatest <strong>{<br>        </strong>flowTextView.<em>text </em>= <strong>it<br>    }<br>}</strong></pre><pre>// combining multiple flows<br>val <em>flow </em>= <em>flow</em>&lt;String&gt; <strong>{<br>    </strong>emit(&quot;Loading&quot;)<br>    val innerFlow = <em>flow</em>&lt;String&gt; <strong>{<br>        </strong>emit(&quot;inner&quot;)<br>    <strong>}<br>    </strong>emitAll(innerFlow)<br><strong>}</strong></pre><p>Flows are usually cold. This means, that <strong>a </strong>cold <strong>flow only emits data when it is collected </strong>(or consumed). Flow does not emit anything values even if there is no collector. But, a cold flow can be converted to ahot flow:</p><pre>val normalFlow = <em>flow </em><strong>{<br>    </strong>emit(&quot;Test&quot;)<br><strong>}<br></strong>val hotFlow: StateFlow&lt;String&gt; =<br>    normalFlow.<em>stateIn</em>(<br>        scope = <em>viewModelScope</em>,<br>        started = SharingStarted.Lazily,<br>        initialValue = &quot;my initial value&quot;<br>    )</pre><h3>SharedFlow</h3><p>Flow’un hot versiyonu. This means, <strong>keep emitting values even if there are no collectors</strong>.</p><p>Name itself says it is shared, this flow can be shared by multiple consumers, I mean if multiple collect calls happening on the SharedFlow there will be a single flow which will get shared across all the consumers, unlike normal flow.</p><pre>// viewModel<br>private val _sharedFlow = <em>MutableSharedFlow</em>&lt;String&gt;()<br>val sharedFlow: SharedFlow&lt;String&gt; = _sharedFlow.<em>asSharedFlow</em>()</pre><pre>fun triggerSharedFlow() {<br>    <em>viewModelScope</em>.<em>launch </em><strong>{<br>        </strong>_sharedFlow.emit(value = &quot;SharedFlow &quot;)<br>    <strong>}<br></strong>}</pre><pre><em>// activity/fragment/view<br>lifecycleScope</em>.launchWhenStarted <strong>{<br>    </strong>viewModel.sharedFlow.collectLatest <strong>{<br>        </strong>Snackbar.make(binding.<em>root</em>, <strong>it</strong>, Snackbar.<em>LENGTH_SHORT</em>).show()<br>    <strong>}<br>}</strong></pre><p>hot flow’ların collect işlemi XXscope.launch içerisinde olmamalı, <a href="https://developer.android.com/reference/kotlin/androidx/lifecycle/LifecycleCoroutineScope">LifecycleCoroutineScope</a> extension’ları olan launchWhenStarted, launchWhenResumed ya da launchWhenCreatedile kullanılmalı. Çünkü flow’lar lifecycle aware değiller. hot flow’lar da collector/consumer’ı olmasa da emit etmeye devam ettiği için, launch ile kullanırsak bağlı oldugu scope sonlandırılınca kendisi hala dinlemeye devam eder.<br>Bunu engellemek yani lifecycle’a bağlamak için launchWhenStarted, launchWhenResumed ya da launchWhenCreated methodları ile kullanılır. Those collectors will automatically be paused and resumed in sync with the component’s Lifecycle.</p><h3>StateFlow</h3><p>SharedFlow’un state tutan versiyonu. Burda state’den kasıt, o anki değeri. Yani flow’ların liveData’da kullandığımız gibi .value access’i yok. Bu sebeple flow kullandığımızda, mesela device rotate edildiğinde data’nın son halini’ini kaybediyoruz çünkü hiçbir yerde tutulmuyor. Bunu sağlayacak flow yapısı, livedata alternatifi olan StateFlow</p><pre>// viewModel<br>private val _stateFlow = <em>MutableStateFlow</em>(&quot;Hello World&quot;)<br>val stateFlow: StateFlow&lt;String&gt; = _stateFlow.<em>asStateFlow</em>()</pre><pre>fun triggerStateFlow() {<br>    _stateFlow.value = &quot;StateFlow&quot;<br>}</pre><pre><em>// activity/fragment/view<br>lifecycleScope</em>.launchWhenStarted <strong>{<br>    </strong>viewModel.stateFlow.collectLatest <strong>{<br>        </strong>binding.stateFlowTextView.<em>text </em>= <strong>it<br>    }<br>}</strong></pre><p>StateFlow sadece değeri değiştiğinde collector tetiklenir. Yeni gelen veri ile eskisi aynı olursa tetiklenmez, farklı is tetiklenir. Yani sadece state değiştiğinde tetikler. liveData ise value’si set edildiğinde observer’ı tetiklenir, önceki değeri ile yenisi aynı olsa bile tetiklenir.</p><p>StateFlow hot flow olduğu için, SharedFlow gibi launchWhenStarted, launchWhenResumed ya da launchWhenCreated ile collect edilmeli.</p><h4>Differences</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KANkJZpR3TZLHhdVRfJAA.png" /></figure><h4>When to Use</h4><ul><li>Use StateFlow as alternative of the livedata , to hold state of the data.</li><li>Use SharedFlow to send one-time events like showing a SnackBar one time you do not need to hold the current state of the data. Mesela api den gelen error’u SharedFlow olarak tutarsak kullanıcı bir kere görür, device rotate oldugunda error’u tekrar görmez. Ayrıca validation işlemlerinde de kullanılabilir. Or you can use when need to use multiple collectors for a flow.</li><li>Use flow — In general think of it like a stream of data flowing in a pipe with both ends having a producer and consumer running on a coroutine.</li></ul><p><strong>.collect() vs .collectLatest()</strong></p><p>The crucial difference between collect() and collectLatest()is that when the original flow emits a new value then the action block for the previous value is cancelled.<br>It can be demonstrated by the following example:</p><pre><em>flow </em><strong>{<br>    </strong>emit(1)<br>    delay(50)<br>    emit(2)<br><strong>}</strong>.<strong>collectLatest</strong> <strong>{ </strong>value <strong>-&gt;<br>    </strong><em>println</em>(&quot;Collecting $value&quot;)<br>    delay(100)<br>    <em>println</em>(&quot;$value collected&quot;)<br><strong>}<br></strong>// Collecting 1<br>// Collecting 2<br>// 2 collected</pre><pre><em>flow </em><strong>{<br>    </strong>emit(1)<br>    delay(50)<br>    emit(2)<br><strong>}</strong>.<strong>collect</strong> <strong>{ </strong>value <strong>-&gt;<br>    </strong><em>println</em>(&quot;Collecting $value&quot;)<br>    delay(100)<br>    <em>println</em>(&quot;$value collected&quot;)<br><strong>}<br></strong>// Collecting 1<br>// 1 collected<br>// Collecting 2<br>// 2 collected</pre><p><strong>.map() vs .flatMap()</strong></p><p>Map is to transform content of the stream.<br>FlatMap to transform stream, used for asynchrnous operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mU9NY58yWUOZRpLsHv1uiA.png" /></figure><p>Sources</p><ul><li><a href="https://kotlinlang.org/docs/flow.html">Asynchronous Flow | Kotlin</a></li><li><a href="https://reactivex.io/documentation/operators.html">ReactiveX - Operators</a></li></ul><p><a href="https://medium.com/mindorks/rxjava-operator-map-vs-flatmap-427c09678784#:~:text=FlatMap%20transforms%20the%20items%20emitted%20by%20an%20Observable%20into%20Observables.&amp;text=So%2C%20the%20main%20difference%20between,to%20map%20over%20asynchronous%20operations">https://medium.com/mindorks/rxjava-operator-map-vs-flatmap-427c09678784#:~:text=FlatMap%20transforms%20the%20items%20emitted%20by%20an%20Observable%20into%20Observables.&amp;text=So%2C%20the%20main%20difference%20between,to%20map%20over%20asynchronous%20operations</a>.</p><p><a href="https://proandroiddev.com/the-real-kotlin-flow-benefits-over-rxjava-c19b99ba6eb9#:~:text=Flow%20by%20itself%20supports%20backpressure,as%20backpressure%20handling%20adds%20overhead%20">https://proandroiddev.com/the-real-kotlin-flow-benefits-over-rxjava-c19b99ba6eb9#:~:text=Flow%20by%20itself%20supports%20backpressure,as%20backpressure%20handling%20adds%20overhead%20</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6Jc6-INantQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6Jc6-INantQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6Jc6-INantQ%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f47cefd99940a05203ea443215fdee/href">https://medium.com/media/52f47cefd99940a05203ea443215fdee/href</a></iframe><ul><li><a href="https://github.com/cimenmus/flows_vs_live_data">GitHub - cimenmus/flows_vs_live_data</a></li><li><a href="https://logidots.com/insights/live-data-flow-shared-flow-state-flow-2/#:~:text=StateFlow(hot%20stream)%20does%20similar,with%20power%20of%20flow&#39;s%20api.">Live data, Flow, Shared flow &amp; State flow - Logidots</a></li><li><a href="https://medium.com/swlh/migrating-from-livedata-to-stateflow-4f28d6889a04">Migrating From LiveData to StateFlow</a></li><li><a href="https://proandroiddev.com/should-we-choose-kotlins-stateflow-or-sharedflow-to-substitute-for-android-s-livedata-2d69f2bd6fa5">Substituting Android&#39;s LiveData: StateFlow or SharedFlow?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50906c521d17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Cheatsheet 5: Scope Functions]]></title>
            <link>https://medium.com/@musticmen/kotlin-cheatsheet-5-scope-functions-faa9d76b361f?source=rss-a4080d72c487------2</link>
            <guid isPermaLink="false">https://medium.com/p/faa9d76b361f</guid>
            <dc:creator><![CDATA[Mustafa İçmen]]></dc:creator>
            <pubDate>Fri, 15 Apr 2022 19:44:17 GMT</pubDate>
            <atom:updated>2022-04-17T14:35:34.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3d__NuNBD6CTQkMW4XIHw.png" /></figure><p><strong>let:</strong> executes the given block of code and <strong>returns the result of its last expression (Unit or value)</strong>. The object is accessible inside the block by the reference it (by default) or a custom name.</p><pre>val empty = &quot;test&quot;.<em>let </em><strong>{<br>    </strong><em>print</em>(<strong>it</strong>)<br>    <strong>it</strong>.<em>isEmpty</em>()<br><strong>}<br></strong><em>println</em>(&quot; is empty: $empty&quot;)<br>// test is empty: false</pre><pre>//----------------------------------------</pre><pre>val empty2: String? = null<br>empty2?.<em>let </em><strong>{<br>    </strong><em>println</em>(<strong>it</strong>)<br><strong>}</strong></pre><pre>//------------------------------</pre><pre>val empty3: String? = null<br>val length = empty3?.<em>let </em><strong>{<br>    </strong><em>println</em>(<strong>it</strong>)<br>    <strong>it</strong>.length<br><strong>} </strong>?: 0<br><em>println</em>(&quot;length: $length&quot;)<br>// length: 0</pre><p><strong>run:</strong> it does the same as let: executes a code block and <strong>returns the result of its last expression (Unit or value)</strong>. The difference is that inside run the object is accessed by this. This is useful when you want to call the object&#39;s methods rather than use it as an argument.</p><pre>val empty = &quot;test&quot;.<em>run </em><strong>{<br>     </strong><em>isEmpty</em>()<br> <strong>}<br> </strong><em>println</em>(&quot; is empty: $empty&quot;)<br> // test is empty: false<br><br>//------------------------------</pre><pre> val empty3: String? = null<br> val length = empty3?.<em>run </em><strong>{<br>     </strong><em>println</em>(&quot;is empty? &quot; + <em>isEmpty</em>())                    <br>     <em>println</em>(&quot;length = $length&quot;)<br>     length<br> <strong>} </strong>?: 0<br> <em>println</em>(&quot;length: $length&quot;)<br>// is empty? : true<br>// length: 0</pre><p>run has two versions: the extension one and non-extension one. We saw the extension version above. Here is the extension sample:</p><pre>val test: String? = null<br>val result = test?.<em>let </em><strong>{<br>    it<br>} </strong>?: <em>run </em><strong>{ </strong>// the same as kotlin.run<br>    &quot;null&quot;<br><strong>}<br></strong><em>println</em>(&quot;result: $result&quot;)<br>// result: null<br><br>// ------------------<br><br><em>run </em><strong>{<br>    </strong><em>println</em>(&quot;Hello World&quot;)<br><strong>}<br></strong>// Hello World</pre><p><strong>with:</strong> can access members of its argument concisely: you can omit the instance name when referring to its members. <strong>Returns the result of its last expression (Unit or value)</strong></p><pre>with(configuration) {<br>    println(&quot;$host:$port&quot;)<br>}</pre><pre>// instead of:<br>println(&quot;${configuration.host}:${configuration.port}&quot;)</pre><p><strong>apply:</strong> executes a block of code on an object and <strong>returns the object itself</strong>. Inside the block, the object is referenced by this. This function is handy for initializing and configuring objects.</p><pre>val adam = Person(&quot;Adam&quot;).apply {<br>    age = 32<br>    city = &quot;London&quot;        <br>}<br>println(adam)</pre><p><strong>also:</strong> works like apply: it executes a given block and <strong>returns the object called</strong>. Inside the block, the object is referenced by it, so it&#39;s easier to pass it as an argument. This function is handy for embedding additional actions, such as logging in call chains.Use <strong>also</strong> for additional actions that don’t alter the object, such as logging or printing debug information.</p><pre>val jake = Person(&quot;Jake&quot;, 30, &quot;Android developer&quot;)<br>    .<em>also </em><strong>{</strong><br>        writeCreationLog(<strong>it</strong>)<br>    <strong>}</strong></pre><h3>Distinctions</h3><p>Because the scope functions are all quite similar in nature, it’s important to understand the differences between them. There are two main differences between each scope function:</p><ul><li>The way to refer to the context object: this or it</li><li>The return value: context object (değişkenin kendisi) or lambda</li></ul><h3>When To Use</h3><p>Geriye değişkenin kendisini dönmek istiyorsak:</p><ul><li>değişkeni configure ediyorsak, değişkenin kendisine değil de variable yada methodlarına ihtiyacımız varsa apply . Çünkü this değişkenin kendisi olduğu için, it yada this yazmadan değişkenin method ve property’lerine erişebiliyoruz.</li><li>değişkeni kullanacaksak (orn. print falan) also . Çünkü it ile değişkene erişiyoruz, also kullansaydık this ile erişmemiz gerekecekti, böyle daha kısa.</li></ul><p>Geriye değer dönmek istemiyorsak yada operasyon sonunda değişkeni değil de başka bir değer dönmek istiyorsak:</p><ul><li>apply gibi kullanalım ama dönüş tipi lambda (Unit yada başka bir değer) dönmek istiyorsak with</li><li>null check yapmak istiyorsak let</li></ul><p>Summary</p><ul><li><strong>apply:</strong><br>Context object: this<br>Return value: context object<br>It’s used to operate on receiver object members, primarily to initialize them. (Objeyi initialize edip geriye return etmek istediğimizde)</li><li><strong>also:-</strong><br>Context object: it<br>Return value: context object<br>It’s used when we need to do additional operations after the object members have been initialized.(Obje initialize edildikten sonra ek işlemler yapıp objeyi return etmek istediğimizde)</li><li><strong>with:-</strong><br>Context object: this<br>Return value: lambda result<br>When calling functions on context objects without supplying the lambda result, ‘with’ is recommended.(apply ve also gibi, fakat objenin kenidisi değil de lambda return etmek istediğimizde, yani Unit yada baska tipte bir value return etmek istediğimizde)</li><li><strong>let: </strong><br>Context object: it <br>Return value: lambda result<br>The let function is frequently used for null safety calls.</li><li><strong>run:</strong><br>Context object: this <br>Return value: lambda result<br>The ‘run’ function is a combination of the ‘let’ and ‘with’ functions. When the object lambda involves both initialization and computation of the return value, this is the method to use. We can use run to make null safety calls as well as other calculations.</li></ul><h3>takeIf and takeUnless</h3><p>In addition to scope functions, the standard library contains the functions takeIf and takeUnless. These functions let you embed checks of the object state in call chains.</p><pre>val number = 100</pre><pre>val evenOrNull = number.takeIf { it % 2 == 0 }<br>val oddOrNull = number.takeUnless { it % 2 == 0 }<br>println(&quot;even: $evenOrNull, odd: $oddOrNull&quot;)<br>// even: 100, odd: null</pre><p>Sources:</p><ul><li><a href="https://kotlinlang.org/docs/scope-functions.html#function-selection">Scope functions | Kotlin</a></li><li><a href="https://play.kotlinlang.org/byExample/06_scope_functions/01_let">Kotlin Playground: Edit, Run, Share Kotlin Code Online</a></li><li><a href="https://www.interviewbit.com/kotlin-interview-questions/">Kotlin Interview Questions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faa9d76b361f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>