<?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 Ömer Şentürk on Medium]]></title>
        <description><![CDATA[Stories by Ömer Şentürk on Medium]]></description>
        <link>https://medium.com/@omersenturk.dev?source=rss-80278af9146d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V4xN6f1OljNaS3qc0Te_HQ.jpeg</url>
            <title>Stories by Ömer Şentürk on Medium</title>
            <link>https://medium.com/@omersenturk.dev?source=rss-80278af9146d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:13:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omersenturk.dev/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[Android Clean Architecture & Modern Architecture]]></title>
            <link>https://medium.com/@omersenturk.dev/android-clean-architecture-modern-architecture-0c871404510f?source=rss-80278af9146d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c871404510f</guid>
            <category><![CDATA[android-cleanarchitecture]]></category>
            <category><![CDATA[modern-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ömer Şentürk]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 19:44:34 GMT</pubDate>
            <atom:updated>2026-01-11T19:52:33.480Z</atom:updated>
            <content:encoded><![CDATA[<p>When refactoring existing code or developing new features becomes a painful process and fixing one issue ends up breaking multiple others the root cause is often an overly tight coupling between the <strong>Domain layer</strong> and external technologies such as databases, UI frameworks or other infrastructure concerns.</p><p>By adopting <strong>Clean Architecture</strong>, we invert this dependency direction, ensuring that the core business logic remains independent of implementation details. This approach results in software that is <strong>highly testable, flexible, and sustainable</strong> over the long term.</p><h4>Dependency Rule</h4><p>The most critical rule of Clean Architecture is <strong>the Dependency Rule</strong>. This rule states that outer layers must always depend on inner layers, while inner layers must have absolutely no knowledge of the outer layers.</p><ul><li><strong>The Domain</strong> is the boss. It defines <em>what</em> the app does.</li><li><strong>The Presentation &amp; Data layers</strong> are just plugins. They define <em>how</em> it’s done.</li></ul><p><strong>How It Looks in Practice</strong> Instead of your Activity talking directly to a database implementation, it talks to a UseCase. That UseCase talks to a Repository <em>Interface</em>.</p><ul><li><strong>Domain:</strong> Says, “I need a User.&quot; (Interface)</li><li><strong>Data:</strong> Says, “Here is that User from Room/Retrofit.&quot; (Implementation)</li></ul><p>This separation is the real superpower. Since your Domain layer doesn’t depend on Android libraries, you can test your business logic quickly on your machine without needing to launch an emulator.</p><p>Here is the basic diagram that visualizes this architecture:</p><pre>:presentation (UI layer)<br>   └── Activity-Fragment -&gt; ViewModel -&gt; UseCase<br><br>:data<br>   └── RepositoryImpl (Retrofit + Room + Cache)<br><br>:domain<br>   ├── model <br>   ├── usecase<br>   └── repository (interfaces)</pre><blockquote>Repository interfaces are defined in the <strong>Domain</strong> layer.<br>The concrete implementations are provided in the <strong>Data</strong> layer.<br>The <strong>Presentation</strong> layer does not directly access the Data layer.</blockquote><p>The greatest advantage of this structure is <strong>testability</strong>. With this architecture, the Domain layer becomes completely isolated from external dependencies, significantly improving its testability.</p><h4>Modern Android Architecture</h4><p><strong>Modern Android Architecture</strong> (MVVM, Repository pattern, state management, Flow, Coroutines) is often treated as sufficient on its own. However, this structure:</p><blockquote>When layer boundaries are not clearly defined,<br> when ViewModels become bloated with business logic,<br> and when data sources leak directly into the UI layer.</blockquote><p>it gradually becomes unsustainable. When Clean Architecture is used together with Modern Android components, we not only write clean code but also achieve far more tangible long-term benefits.</p><blockquote>MVVM focuses solely on UI state management.<br> Business logic is extracted from the ViewModel and moved into Use Cases.<br> Since Use Cases are independent of the UI, unit testing becomes easier.<br> Changes made in one layer have less impact on other layers.<br> The codebase becomes more resilient to feature-based growth.</blockquote><p>In conclusion, Clean Architecture may initially give the impression of requiring a significant amount of boilerplate code (creating Use Cases, writing interfaces, mappers, and so on). However, once the architecture matures, adding a new feature or modifying an existing one becomes exponentially faster and safer compared to an MVVM structure that has evolved into spaghetti code.</p><h4>Other Articles</h4><ul><li><a href="https://medium.com/@omersenturk.dev/3-ways-to-access-ui-components-in-android-pros-and-cons-85364391b483">3 Ways to Access UI Components in Android: Pros and Cons</a></li><li><a href="https://medium.com/@omersenturk.dev/using-broadcastreceiver-in-android-7506cf3087c6">Using BroadcastReceiver in Android</a></li><li><a href="https://medium.com/@omersenturk.dev/kotlin-higher-order-function-and-lambdas-9dc21d0eec91">Higher-Order Functions and Lambda Expressions in Kotlin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c871404510f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Ways to Access UI Components in Android: Pros and Cons]]></title>
            <link>https://medium.com/@omersenturk.dev/3-ways-to-access-ui-components-in-android-pros-and-cons-85364391b483?source=rss-80278af9146d------2</link>
            <guid isPermaLink="false">https://medium.com/p/85364391b483</guid>
            <category><![CDATA[findviewbyid]]></category>
            <category><![CDATA[android-ui]]></category>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[andorid]]></category>
            <category><![CDATA[view-binding]]></category>
            <dc:creator><![CDATA[Ömer Şentürk]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 13:33:07 GMT</pubDate>
            <atom:updated>2025-10-18T19:32:48.895Z</atom:updated>
            <content:encoded><![CDATA[<h3>DataBinding vs ViewBinding in Android: Which One Should You Use?</h3><p>Hello everyone! As you know, there are three ways to access UI components from an Activity or Fragment in Android: findViewById, DataBinding, and ViewBinding.<br>Today, I will explain the advantages and disadvantages of these three methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pavl8QjWETEeYt1_" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>FindViewById</h4><p>When we first start Android development, most of us use the basic findViewById method. But why is it rarely preferred in modern projects? There are several reasons:</p><p><strong>🔴Does Not Support Null Safety</strong></p><p>With findViewById, we create an ID-based connection to UI components. But what happens if the specified ID does not exist in the XML? The app crashes. To handle this, we must manually perform null checks.</p><p>Consider the following scenario where the XML component with the ID buttonMessage does not exist and we handle it with a manual null check:</p><pre>// Error leading to a crash:<br><br>val messageButton: Button = findViewById(R.id.buttonMessage) // Not in XML<br><br>messageButton.setOnClickListener {<br>    Toast.makeText(this, &quot;Message Button Clicked&quot;, Toast.LENGTH_SHORT).show()<br>}</pre><pre>// Solution with manual null check:<br><br>val messageButton: Button? = findViewById(R.id.buttonMessage)<br><br>messageButton?.setOnClickListener {<br>    Toast.makeText(this, &quot;Message Button Clicked&quot;, Toast.LENGTH_SHORT).show()<br>}</pre><blockquote>With this manual null check, the app does not crash even if the component with ID buttonMessage is missing. However, since the component does not exist, the setOnClickListener function will not execute, which can cause other functional issues.</blockquote><p><strong>🔴Does Not Support Type Safety</strong></p><p>Another issue with findViewById is type mismatch between the expected type and the type of the component. This leads to crashes and ClassCastException errors.</p><pre>// &lt;!-- XML --&gt;<br>&lt;Button<br>    android:id=&quot;@+id/textViewMessage&quot;<br>    android:layout_width=&quot;wrap_content&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:text=&quot;Click Me&quot;/&gt;<br><br>//Activity <br>val message: TextView = findViewById(R.id.textViewMessage)<br>message.text = &quot;Hi&quot;</pre><blockquote>Here, the message variable is defined as a TextView, but the ID in XML actually points to a Button. This type mismatch causes the app to crash. The solution is to use <strong>ViewBinding</strong> or <strong>DataBinding</strong>.</blockquote><p><strong>🔴Prone to Errors</strong></p><p>Another common problem is that we often want to use UI components throughout multiple functions in an Activity or Fragment. Typically, we declare these components at the top of the class using lateinit. If we forget to initialize them in onCreate or onViewCreated, the app crashes.</p><pre>class MainActivity : AppCompatActivity() {<br><br>    // Declare UI components at the top of the class<br>    private lateinit var messageButton: Button<br>    private lateinit var messageText: TextView<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        <br>        // Initialize UI components<br>        initUI()<br>        <br>        // Use the components<br>        messageButton.setOnClickListener {<br>            Toast.makeText(this, &quot;Message Button Clicked&quot;, Toast.LENGTH_SHORT).show()<br>            messageText.text = &quot;Hi&quot;<br>        }<br>    }<br><br>    private fun initUI() {<br>        messageButton = findViewById(R.id.buttonMessage)<br>        messageText = findViewById(R.id.textViewMessage)<br>    }<br>}</pre><blockquote>As you know, real applications usually have more than just a couple of UI components. Forgetting to initialize a component and then attempting to use it will cause a crash.</blockquote><blockquote>To reduce this risk, it is common to create an initUI function to centralize all initialization, and then call it in onCreate or onViewCreated.</blockquote><blockquote>This helps reduce errors but is not a perfect solution—forgotten or incorrectly initialized components can still cause crashes.</blockquote><p><strong>🔴R.id Scans All ID’s</strong></p><p>R.id represents a list of all view IDs in the XML. Every time findViewById is called, it searches this list to find the specified ID in the layout. This makes it less performant compared to modern approaches.</p><p>For these reasons, findViewById is no longer widely preferred in modern Android projects.</p><h4>ViewBinding</h4><p>Another method we can use to access UI components is <strong>ViewBinding</strong>. This method allows us to access components directly in a <strong>type-safe</strong> way. In addition, a <strong>binding class</strong> is generated for each layout file. Since the components in the layout can be accessed directly through this class, <strong>null safety</strong> is also guaranteed.</p><p>🟢 Type Safety guaranteed<br>🟢 Null Safety guaranteed<br>🟢 Less boilerplate code<br>🟢 Lower chance of errors compared to findViewById</p><h4><strong>ViewBinding Setup</strong></h4><pre>//build.grandle(:app)<br><br>android {<br>    ...<br>    buildFeatures {<br>        viewBinding = true<br>    }<br>}</pre><p>After completing the setup, we will be able too access the UI components in our activities and fragments with a single line of code. I will first demonstrate how to access them in an activity, and then in a fragment.</p><p><strong>Using ViewBinding in an Activity</strong></p><pre>class MainActivity : AppCompatActivity(){<br><br>  // Declare the binding variable for ActivityMainBinding<br>  private lateinit var binding: ActivityMainBinding<br><br>  override fun onCreate(savedInstanceState: Bundle?){<br>      super.onCreate(savedInstanceState)<br><br>      // Inflate the layout using ViewBinding<br>      binding = ActivityMainBinding.inflate(layoutInflater)<br>      // Set the root view of the binding as the content view<br>      setContentView(binding.root)<br>      <br>      // Access UI components directly using the binding object<br>      binding.button.setOnClickListener{<br>         binding.textViewMessage.text = &quot;Hi ViewBinding&quot;<br>      }<br>  }<br>}</pre><blockquote>For activity_main.xml the ActivityMainBinding class has been generated.<br>Thanks to ActivityMainBinding, we can access all UI components with an ID directly through the binding object.</blockquote><p><strong>Using ViewBinding in a Fragment</strong></p><pre>class HomeFragment : Fragment() {<br><br>    // _binding is nullable to prevent memory leaks<br>    private var _binding: FragmentHomeBinding? = null<br>    private val binding get() = _binding!!<br><br>    override fun onCreateView(<br>        inflater: LayoutInflater, container: ViewGroup?,<br>        savedInstanceState: Bundle?<br>    ): View {<br>        // Inflate the layout using ViewBinding<br>        _binding = FragmentHomeBinding.inflate(inflater, container, false)<br>        // Return the root view of the binding<br>        return binding.root<br>    }<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br><br>        // Access UI components directly using the binding object<br>        binding.button.setOnClickListener {<br>            binding.textViewMessage.text = &quot;Hi ViewBinding&quot;<br>        }<br>    }<br><br>    override fun onDestroyView() {<br>        super.onDestroyView()<br>        // Set _binding to null to avoid memory leaks<br>        _binding = null<br>    }<br>}</pre><blockquote>When using fragments, there is an important point to keep in mind: To prevent <strong>memory leaks</strong>, we should set the binding to null inside onDestroyView().</blockquote><h4>DataBinding</h4><p>Data Binding can also be used to access UI components. Just like ViewBinding, it provides type-safety and null-safety, and it automatically generates a binding class for each layout file.</p><p>However, unlike ViewBindingand findViewById:</p><ul><li>It provides two-way binding support, allowing changes in the UI to automatically reflect in the ViewModel.</li><li>It allows us to bind data directly to the UI through XML.</li></ul><p>Therefore, Data Binding is not just a tool for accessing UI components; it is also a mechanism that keeps the data and the UI in sync.</p><h4>DataBinding Setup</h4><pre>//build.grandle(:app)<br><br>android {<br>    ...<br>    buildFeatures {<br>        dataBinding = true<br>    }<br>}</pre><p>We usually start our layout files with LinearLayout or ConstraintLayout; however, if we are using Data Binding, the root element of our layout file must be &lt;layout&gt;.</p><pre>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br><br>    &lt;data&gt;<br>        &lt;variable<br>            name=&quot;user&quot;<br>            type=&quot;com.example.app.User&quot; /&gt;<br>    &lt;/data&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:orientation=&quot;vertical&quot;&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;@{user.name}&quot; /&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;@{user.job}&quot; /&gt;<br><br>    &lt;/LinearLayout&gt;<br>&lt;/layout&gt;</pre><blockquote>Variables to be used in the XML are defined inside the &lt;data&gt; block.<br>The @{} expression is used to bind a variable directly to the XML.<br>The <strong>name</strong> parameter inside the &lt;variable&gt; tag represents the variable name that we will use in the XML.<br>The <strong>type</strong> parameter specifies the class (model/object) type of this variable.</blockquote><p><strong>User Model Used with Data Binding in Layout</strong></p><pre>package com.example.app<br><br>data class User(<br>    val name: String,<br>    val job: String<br>)</pre><p><strong>Using DataBinding in an Activity</strong></p><pre>class MainActivity : AppCompatActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        <br>        val binding: ActivityMainBinding =<br>            DataBindingUtil.setContentView(this, R.layout.activity_main)<br><br>        val user = User(&quot;Jhon&quot;,&quot;Android Developer&quot;)<br>        binding.user = user<br>    }<br>}</pre><blockquote>By assigning binding.user = user, the user object is linked to the variable defined in the XML. This allows the TextView elements to automatically display the corresponding data (name and job) from the User model.</blockquote><p><strong>Using DataBinding in a Fragment</strong></p><pre>class MyFragment : Fragment() {<br>    private var _binding: FragmentMyBinding? = null<br>    private val binding get() = _binding!!<br><br>    override fun onCreateView(<br>        inflater: LayoutInflater, container: ViewGroup?,<br>        savedInstanceState: Bundle?<br>    ): View {<br>        _binding = DataBindingUtil.inflate(inflater, R.layout.fragment_my, container, false)<br>        val user = User(&quot;Alice&quot;, &quot;Mobile Developer&quot;)<br>        binding.user = user<br>        return binding.root<br>    }<br><br>    override fun onDestroyView() {<br>        super.onDestroyView()<br>        _binding = null<br>    }<br>}</pre><blockquote>Just like in ViewBinding, there is a risk of memory leaks with DataBinding. Therefore, _binding should be set to null inside onDestroyView().</blockquote><h4><strong>Why DataBinding Can Be Problematic :</strong></h4><p>🔴 <strong>Maintenance Difficulty</strong><br>Debugging code in large projects that use DataBinding can be challenging. Errors are often hidden within the XML, surfacing only at runtime.</p><p>🔴 <strong>Slower than ViewBinding</strong><br>DataBinding uses expressions and variables in XML, which increases compile-time compared to ViewBinding.</p><p>🔴 <strong>More complex for junior developers</strong><br>DataBinding offers features like XML variables, observables, and two-way binding. These constructs can be difficult for less experienced developers to understand.</p><p><strong>Overall, if we were to compare:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWPhIcXSFdVO48QB22lajg.png" /></figure><p>Considering all these points, if you’re starting a project from scratch, I recommend using ViewBinding.</p><h4>Summary</h4><p>This article compared three ways to access UI components in Android: findViewById, ViewBinding, and DataBinding. We saw that findViewById is the oldest method but lacks type safety, null safety, and performance, making it less suitable for modern projects. ViewBinding improves safety and reduces boilerplate code while remaining fast and reliable, making it the recommended choice for most cases. DataBinding offers the same benefits as ViewBinding plus advanced features like two-way data binding and XML-based data expressions, but at the cost of slower builds and higher complexity. Overall, for new projects, ViewBinding is suggested as the best balance between safety, performance, and simplicity.</p><h3>Topic List</h3><blockquote>What are the methods for accessing UI components in Android?<br>What are the advantages of the findViewById method?<br>What are the disadvantages of the findViewById method?<br>What are the advantages of the ViewBinding method?<br>What are the disadvantages of the ViewBinding method?<br>What are the advantages of the DataBinding method?<br>What are the disadvantages of the DataBinding method?<br>Comparison of findViewById, ViewBinding, and DataBinding methods.<br>What should be considered when using ViewBinding and DataBinding?<br>Memory leak risks in ViewBinding and DataBinding and how to prevent them.</blockquote><p><strong>Source</strong></p><p><a href="https://developer.android.com/topic/libraries/view-binding">https://developer.android.com/topic/libraries/view-binding</a><br><a href="https://developer.android.com/topic/libraries/data-binding">https://developer.android.com/topic/libraries/data-binding/</a></p><h4>Other Articles</h4><ul><li><a href="https://medium.com/@omersenturk.dev/understanding-launch-modes-in-android-how-activities-and-backstack-work-f5a313c1e603">Understanding Launch Modes in Android: How Activities and BackStack Work</a></li><li><a href="https://medium.com/@omersenturk.dev/using-broadcastreceiver-in-android-7506cf3087c6">Using BroadcastReceiver in Android</a></li><li><a href="https://medium.com/@omersenturk.dev/kotlin-higher-order-function-and-lambdas-9dc21d0eec91">Higher-Order Functions and Lambda Expressions in Kotlin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85364391b483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Launch Modes in Android: How Activities and BackStack Work]]></title>
            <link>https://medium.com/@omersenturk.dev/understanding-launch-modes-in-android-how-activities-and-backstack-work-f5a313c1e603?source=rss-80278af9146d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5a313c1e603</guid>
            <category><![CDATA[android-launch-mode]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[andorid]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Ömer Şentürk]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 09:43:20 GMT</pubDate>
            <atom:updated>2025-08-22T09:43:20.030Z</atom:updated>
            <content:encoded><![CDATA[<p>With launch modes, we can control how our application behaves when navigating between different screens. In Android, every time we move from one activity to another, the system needs to decide whether to create a brand-new instance of that activity or bring back an existing one. This behavior directly affects how the BackStack is managed, how much memory is used, and what the user experiences when pressing the back button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b-yWUj_FbuEshxlT" /><figcaption>Photo by <a href="https://unsplash.com/@redaquamedia?utm_source=medium&amp;utm_medium=referral">Denny Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In simple terms, launch modes allow us to define the “rules of navigation” for our activities. Do we want each navigation to always open a fresh copy? Or should the app recognize that the activity is already open and simply reuse it? By choosing the right launch mode, we can make our app’s navigation smoother, avoid unexpected duplicates in the BackStack, and create a more predictable user flow.</p><h4>Standard Launch Mode</h4><p>This is the default launch mode. Each time startActivity is called, a new activity state is added to the BackStack. If an existing activity is launched again with startActivity , the existing one is not reused. Instead, a new instance is created. As a result, the BackStack may contain multiple copies of the same activity (each with its own state).</p><p>Any UI changes made in one instance do not affect other instances. In other words, each copy of the activity operates independently, so modifying the UI in one instance will not change what appears in the others</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_I8V91UNWYHmb1gWZhzE5g.jpeg" /></figure><h4>SingleTop</h4><p>If the activity being launched already exists at the top of the BackStack (the one currently visible), startActivity will not create a new copy. Instead, the existing activity receives onNewIntent , and onCreate is not called.</p><p>The launch mode of an activity can be defined in Manifest.xml, or overridden in code by using intent flags:</p><pre> //Manifes.xml<br> &lt;activity<br> android:name=&quot;.SecondActivity&quot;<br> android:launchMode=&quot;singleTop&quot; /&gt;<br><br>//Intent Flag<br>val intent = Intent(this, SecondActivity::class.java).apply{<br>  flag = Intent.FLAG_ACTIVITY_SINGLE_TOP<br>}<br>startActivity(intent)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WI7JdXBPGPF545_7wdl9jQ.jpeg" /></figure><h4>SingleTask</h4><p>Unlike SingleTop, if an activity being launched with startActivity already exists in the BackStack, it is moved to the top of the BackStack and starts with the <strong>onNewIntent() </strong>method. Before being moved, all activities above it are destroyed.</p><p>However, if the activity does not already exist in the BackStack, a new instance is added.</p><pre> //Manifes.xml<br> &lt;activity<br> android:name=&quot;.SecondActivity&quot;<br> android:launchMode=&quot;singleTask&quot; /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ay--5TbvTfsLHc1Sc4WMrQ.jpeg" /></figure><h4>TaskAffinity/SingleTask</h4><p>Defines which task an activity prefers to belong to.By itself, it does not create a new task. A new task will only be created if:</p><p>The activity uses launchMode=”singleTask” / singleInstance / singleInstancePerTask in the manifest or if the Intent includes FLAG_ACTIVITY_NEW_TASK.</p><p>The new task will have its own BackStack. Two separate tasks will appear on the Overview (recent apps) screen.</p><pre>//Manifest.xml<br> &lt;activity<br> android:name=&quot;.SecondActivity&quot;<br> android:launchMode=&quot;singleTask&quot;<br> android:taskAffinity=&quot;com.example&quot; /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKXyXCkErQQC7i6nDdtqgw.jpeg" /></figure><h4>SingleInstance</h4><p>SingleInstance allows a new task to be created, but no TaskAffinity is assigned to this task. If an activity within a SingleInstance task launches a new activity using startActivity , the new activity will open in the <strong>main task</strong>(In this example, Task1 is the main Task).</p><p>This guarantees that the SingleInstance task contains only a single activity. In the Overview (recent apps) screen, the SingleInstance task appears as a single task window.</p><pre>//Manifest.xml<br> &lt;activity<br> android:name=&quot;.SecondActivity&quot;<br> android:launchMode=&quot;singleInstance&quot; /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWO4IKhllHi9zwBTmPRtOQ.jpeg" /></figure><p>When the back button is pressed while in ThirdActivity, the navigation follows this route:</p><p><strong>ThirdActivity → MainActivity → SecondActivity</strong></p><p>If an attempt is made to navigate to SecondActivity again using <strong>startActivity</strong> while in ThirdActivity, the <strong>onNewIntent() </strong>method of SecondActivity is invoked.</p><h4>SingleInstancePerTask</h4><p>Similar to SingleInstance, it creates a new task without requiring Task Affinity. However, unlike SingleInstance, the new task’s BackStack <strong>can hold multiple activities.</strong></p><pre>//Manifest.xml<br> &lt;activity<br> android:name=&quot;.SecondActivity&quot;<br> android:launchMode=&quot;singleInstancePerTask&quot; /&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSU4xzZ3fPNHMny599rhEA.jpeg" /></figure><p>As shown in the diagram above, ThirdActivity was opened in the backstack of Task2.</p><h4>Summary</h4><p>In this article, I explained how <strong>Launch Modes</strong> in Android determine the way Activities are managed in the <strong>BackStack</strong>. The choice of launch mode directly impacts memory usage, navigation flow, and how the back button behaves. By defining proper launch modes, developers can avoid duplicate Activity instances and provide a more predictable user experience.</p><h4>Topic List</h4><blockquote>What are launch modes?<br>Relation to the BackStack.<br>Navigation rules and user experience impact.<br>Standart Launch Mode<br>SingleTop<br>SingleTask<br>TaskAffinity / SingleTask<br>SingleInstance<br>SingleInstancePerTask</blockquote><ul><li><a href="https://medium.com/@omersenturk.dev/using-broadcastreceiver-in-android-7506cf3087c6">Using BroadcastReceiver in Android</a></li><li><a href="https://medium.com/@omersenturk.dev/kotlin-higher-order-function-and-lambdas-9dc21d0eec91">Higher-Order Functions and Lambda Expressions in Kotlin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5a313c1e603" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using BroadcastReceiver in Android]]></title>
            <link>https://medium.com/@omersenturk.dev/using-broadcastreceiver-in-android-7506cf3087c6?source=rss-80278af9146d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7506cf3087c6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[broadcastreceiver]]></category>
            <dc:creator><![CDATA[Ömer Şentürk]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 20:25:05 GMT</pubDate>
            <atom:updated>2025-07-20T14:36:12.360Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qO3QA7I7TmZLHYqc" /><figcaption>Photo by <a href="https://unsplash.com/@stenslens?utm_source=medium&amp;utm_medium=referral">Sten Ritterfeld</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Broadcast Receiver is a component that allows us to listen to certain events that occur within the Android operating system or between applications and helps us react to them in the ways we specify.</p><p>Today I will show you two examples that capture and react to airplane mode turning on and off and changes in battery level. But remember, that’s not all you can do with Broadcast Receivers, you can also listen and react to multiple system events.</p><p>Broadcast Receivers can be registered on the Android system in two different ways: static and dynamic. Today, I will show you both methods in an explanatory way, by statically logging airplane mode changes and dynamically logging battery level changes</p><h4>1. Airplane Mode Changes</h4><pre>import android.content.BroadcastReceiver<br>import android.content.Context<br>import android.content.Intent<br>import android.widget.Toast<br><br>class FlightModeReceiver : BroadcastReceiver() {<br>    override fun onReceive(context: Context, intent: Intent?) {<br>        if (intent?.action == Intent.ACTION_AIRPLANE_MODE_CHANGED) {<br>            val isFlightModeOn = intent.getBooleanExtra(&quot;state&quot;, false)<br>            if(isFlightModeOn){<br>              Toast.makeText(context, &quot;Flight Mode On&quot;, Toast.LENGTH_SHORT).show()<br>            }else{<br>              Toast.makeText(context, &quot;Flight Mode Off&quot;, Toast.LENGTH_SHORT).show()<br>            }<br>        }<br>    }<br>}</pre><blockquote>We have created our Broadcast Receiver, now it’s time to introduce it into our application. In this example I will show you how to statically notify it</blockquote><h4>Static Defining Broadcast Receiver with AndroidManifest.xml</h4><pre>&lt;receiver android:name=&quot;.FlightModeReceiver&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;android.intent.action.AIRPLANE_MODE_CHANGED&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/receiver&gt;</pre><blockquote>When defining a static BroadcastReceiver, we first need to add a &lt;receiver&gt; tag to the AndroidManifest.xml file. In the android:name attribute, we write the name of the class we created, prefixed with a dot .FlightModeReceiver). Then, we specify which system events we want to listen to using an &lt;intent-filter&gt; tag. For example, to be notified when airplane mode is turned on or off, we use the android.intent.action.AIRPLANE_MODE_CHANGED filter to track changes in flight mode.</blockquote><h4>2.Battery Level Tracking</h4><p>Now it’s time to register a dynamic Broadcast Receiver. In this example, we will create a BroadcastReceiver that detects when the device’s battery level is low or normalized. This way we will be able to listen to notifications from the system about the battery status</p><pre>class BatteryLevelTracking : BroadcastReceiver() {<br>    override fun onReceive(context: Context?, intent: Intent?) {<br>        when (intent?.action) {<br>            Intent.ACTION_BATTERY_LOW -&gt; {<br>                Toast.makeText(context, &quot;Battery level is low.&quot;, Toast.LENGTH_SHORT).show()<br>            }<br>            Intent.ACTION_BATTERY_OKAY -&gt; {<br>                Toast.makeText(context, &quot;Battery level is back to normal.&quot;, Toast.LENGTH_SHORT).show()<br>            }<br>        }<br>    }<br>}</pre><blockquote>Now, let’s register our BroadcastReceiver dynamically in MainActivity</blockquote><pre>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var batteryReceiver: BatteryLevelTracking<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        batteryReceiver = BatteryLevelTracking()<br><br>        val intentFilter = IntentFilter().apply {<br>            addAction(Intent.ACTION_BATTERY_LOW)<br>            addAction(Intent.ACTION_BATTERY_OKAY)<br>        }<br><br>        registerReceiver(batteryReceiver, intentFilter)<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        unregisterReceiver(batteryReceiver)<br>    }<br>}</pre><blockquote>When we’re done listening to system events, meaning when the app is closing, we must unregister the receiver using unregisterReceiver to avoid memory leaks. Otherwise, the app may cause a memory leak.</blockquote><h4>Custom Broadcast Receiver</h4><p>Finally, I would like to mention that we can listen to ready-made system events, but we can also listen to our own custom system events. We can create our own broadcast event and trigger it as well. Let’s take a look at how to do this.</p><pre>class MyCustomBroadcastReceiver : BroadcastReceiver() { <br>    override fun onReceive(context: Context?, intent: Intent?) {<br>        if (intent?.action == &quot;com.example.CUSTOM_ACTION&quot;) {<br>            val message = intent.getStringExtra(&quot;message&quot;) ?: &quot;No message received&quot;<br>            Toast.makeText(context, message, Toast.LENGTH_SHORT).show() <br>        }<br>    }<br>}</pre><blockquote>We can register MyCustomBroadcastReceiver either dynamically in the code using registerReceiver(), or statically by declaring it in the AndroidManifest.xml file. Below, I chose to register it dynamically.</blockquote><pre>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var customReceiver: MyCustomBroadcastReceiver<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        customReceiver = MyCustomBroadcastReceiver()<br>        val filter = IntentFilter(&quot;com.example.CUSTOM_ACTION&quot;)<br>        registerReceiver(customReceiver, filter)<br><br>        val button: Button = findViewById(R.id.myButton)<br>        button.setOnClickListener {<br>            val intent = Intent(&quot;com.example.CUSTOM_ACTION&quot;).apply {<br>                putExtra(&quot;message&quot;, &quot;Say Hi! My Custom Broadcast Receiver!&quot;)<br>            }<br>            sendBroadcast(intent)<br>        }<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        unregisterReceiver(customReceiver)<br>    }<br>}</pre><h4>Summary</h4><p>This article explained how BroadcastReceivers work in Android and how they can be used to respond to both system and custom events. We looked at two ways to register receivers: statically through the AndroidManifest.xml file and dynamically in code. As examples, we listened to airplane mode changes using a static receiver, tracked battery level changes dynamically, and created a custom broadcast to show how apps can send and receive their own events. Proper use of BroadcastReceivers helps create flexible and responsive applications, as long as we remember to unregister dynamic receivers to prevent memory leaks.</p><h4>Topic List</h4><blockquote>What is a BroadcastReceiver and how it works<br>Static vs Dynamic BroadcastReceiver registration<br>Listening to airplane mode changes (static example)<br>Tracking battery level (dynamic example)<br>How to create and use a custom broadcast<br>Using registerReceiver() and unregisterReceiver() properly<br>Avoiding memory leaks when using dynamic receivers</blockquote><h4>Source</h4><p><a href="https://developer.android.com/develop/background-work/background-tasks/broadcasts">https://developer.android.com/develop/background-work/background-tasks/broadcasts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7506cf3087c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Higher-Order Functions and Lambda Expressions in Kotlin]]></title>
            <link>https://medium.com/@omersenturk.dev/kotlin-higher-order-function-and-lambdas-9dc21d0eec91?source=rss-80278af9146d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dc21d0eec91</guid>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[android-developers]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[kotlin-lambdas]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Ömer Şentürk]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 13:45:53 GMT</pubDate>
            <atom:updated>2025-07-04T06:17:46.792Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i_v2QrdSEEA3QwKR" /><figcaption>Photo by <a href="https://unsplash.com/@louis993546?utm_source=medium&amp;utm_medium=referral">Louis Tsai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Higher-order functions are functions that can take another function as an argument or return a function. When used with lambda expressions, they are structures that reduce code repetition, allowing us to write more flexible and concise code. By flexible structures, we mean that while a regular function performs a single task, higher-order functions enable us to perform multiple tasks with the same structure by writing shorter code.<br>To better understand the topic, let’s convert a regular function into a higher-order function.</p><pre>fun main() {<br>    val sum = calculate(5, 7, &#39;+&#39;)<br>    val subtraction = calculate(5, 7, &#39;-&#39;)<br>    val multiplication = calculate(5, 7, &#39;*&#39;)<br>    val division = calculate(5, 7, &#39;/&#39;)<br>}<br><br>// Regular Function<br>fun calculate(num1: Int, num2: Int, operation: Char): Int {<br>    val result = when (operation) {<br>        &#39;+&#39; -&gt; num1 + num2<br>        &#39;-&#39; -&gt; num1 - num2<br>        &#39;*&#39; -&gt; num1 * num2<br>        &#39;/&#39; -&gt; num1 / num2<br>        else -&gt; 0<br>    }<br>    return result<br>}</pre><blockquote>The code above works, but it doesn’t quite adhere to clean code principles. The calculate function is overloaded with too many responsibilities, and when we want to add a new operation, we need to modify both the calculate and main functions. Instead, if we use a higher-order function, we can make the code both more readable and much more flexible.</blockquote><h4>1-Function-Taking Higher-Order Function as an Argument</h4><pre>fun main() {<br>    // -&gt; 1st Approach<br>    // Passing the function argument directly with a lambda.<br>    val sum = calculate(5, 7) { a, b -&gt; a + b }<br>    val subtraction = calculate(3, 1) { a, b -&gt; a - b }<br>    val multiplication = calculate(5, 8) { a, b -&gt; a * b }<br>    val division = calculate(12, 2) { a, b -&gt; a / b }<br>    val modulo = calculate(19, 3) { a, b -&gt; a % b }<br>    val max = calculate(55, 29) { a, b -&gt; maxOf(a, b) }<br>    val min = calculate(55, 29) { a, b -&gt; minOf(a, b) }<br>     <br>    // 2nd Approach<br>    // Storing the function in a variable and passing it as a reference.<br>    val sum2 = calculate(5, 7, sumFunction) <br>    val subtraction2 = calculate(3, 1, subsractionFunc)<br>    val multiplication2 = calculate(5, 8, multiplyFunc)<br>    val division2 = calculate(12, 2, ::divFunc)<br>    // To use ::, we need a normal function.<br>    // With ::, only the body of the function is taken.<br>}<br>// Higher-order Function<br>fun calculate(num1: Int, num2: Int, operation: (Int, Int) -&gt; Int): Int {<br>    return operation(num1, num2)<br>}<br><br>// Normal function<br>fun divFunc(a: Int, b: Int): Int = a / b<br>// Storing the function in a variable<br>val sumFunction = { a: Int, b: Int -&gt; a + b }<br>// Anonymous function<br>val subsractionFunc = fun(a: Int, b: Int): Int { return a - b }<br>// Expression body Anonymous function<br>val multiplyFunc = fun(a: Int, b: Int): Int = a * b</pre><blockquote>Thanks to higher-order functions, we achieve a much more readable and flexible structure with less code when adding new operations. As we recall from the definition of higher-order functions, we said, “Higher-order functions are functions that can take another function as an argument or return a function.” For example, the operation parameter in our code represents another function, allowing the calculate function to be reused for different operations.</blockquote><h4>2-Higher-Order Function That Returns a Function</h4><pre>fun main() {<br>    val repeat3Times = repeater(3)<br>    val repeat5Times = repeater(5)<br><br>    println(repeat3Times(&quot;Kotlin! &quot;))  // Kotlin! Kotlin! Kotlin!<br>    println(repeat5Times(&quot;Hi! &quot;))  // Hi! Hi! Hi! Hi! Hi! <br>}<br>//Higher-order Function <br>fun repeater(times: Int): (String) -&gt; String {<br>    return { text -&gt; text.repeat(times) }<br>}</pre><h4>Catching a Single Parameter with the “it” Keyword in Lambda Expressions</h4><p>In higher-order functions, we can capture the incoming parameter using the it keyword in single-parameter lambda operations. However, if multiple parameters are involved, we need to name the parameters.</p><pre>fun main() {<br>    val numberList = listOf(20, 12, 3, 5, 77, 95, 81, 6)<br>    // `it` corresponds to each element in the list<br>    val count = numberList.filter { it &gt; 50 }.count()<br>    println(&quot;Result: $count&quot;) // Result: 3<br>}</pre><h4>Standard Kotlin Library Higher-Order Functions</h4><p>In Kotlin, while we can write our own higher-order functions, there are also ready-made functions defined in the standard library. We can use these functions on their own or combine them with our own higher-order functions to create more powerful and flexible code.</p><pre>fun main() {<br>    val numbers = listOf(5, 3, 19, 12)<br>    // reduce: Sums the numbers in the list<br>    val total = numbers.reduce { total, number -&gt; total + number }<br>    <br>    // filter: Selects numbers greater than 10 =&gt; {19, 12}<br>    val largeNumbers = numbers.filter { it &gt; 10 }<br>    <br>    // map: Multiplies each number by 2 using `calculate` {19*2 | 12*2}<br>    val doubled = largeNumbers.map { calculate(it, 2) { a, b -&gt; a * b } }<br><br>    // any: Checks if there is any number less than 0 in the list<br>    val isNegative = numbers.any { it &lt; 0 }<br>    <br>    // forEach: Iterates over the list<br>    doubled.forEach { println(&quot;Result: $it&quot;) } // Result: 38 - 24<br>    println(&quot;Sum of Numbers: $total&quot;) // Sum of Numbers: 39<br>    println(isNegative) // false<br>}<br><br>fun calculate(num1: Int, num2: Int, operation: (Int, Int) -&gt; Int): Int {<br>    return operation(num1, num2)<br>}</pre><blockquote>In addition to the commonly used higher-order functions mentioned above, Kotlin also includes functions such as <em>fold</em>, <em>find</em>, <em>all</em>, <em>count</em>, <em>sorted</em>, and many others. You can access their details and usage examples via the<a href="https://kotlinlang.org/docs/lambdas.html#higher-order-functions"> link.</a></blockquote><h4>Performance in Higher-Order Functions</h4><p>Every time we use a higher-order function, a lambda expression or function object is created in memory. This can lead to the allocation of temporary objects and may result in performance overhead.</p><pre>fun main() {<br>    for (i in 1..1000) {<br>        val prefix = &quot;say $i&quot; <br>        repeatMessage(&quot;Kotlin&quot;) {<br>            println(&quot;${prefix}.Hello ${it}&quot;)<br>        }<br>    }<br>}<br>fun repeatMessage(name: String, action: (String) -&gt; Unit) {<br>    action(name)<br>}</pre><blockquote>In the background, 1,000 lambda objects are created. These objects occupy space on the heap and can lead to performance degradation. To avoid this overhead, we can use the inline modifier.</blockquote><h4>What Is the inline Keyword in Kotlin?</h4><p>When a function is marked with the inline keyword, both the function call and any lambda expressions passed to it are inlined — meaning the compiler replaces the call site with the actual function and lambda code. This eliminates the need to allocate function or lambda objects on the heap, resulting in reduced memory usage and improved performance.</p><pre>fun main() {<br>    for (i in 1..1000) {<br>        val prefix = &quot;say $i&quot;<br>        repeatMessage(&quot;Kotlin&quot;) {<br>            println(&quot;${prefix}.Hello ${it}&quot;)<br>        }<br>    }<br>}<br><br>inline fun repeatMessage(name: String, action: (String) -&gt; Unit) {<br>    action(name)<br>}</pre><blockquote><strong>Important Note!!!!</strong><br>We should not always inline functions. If the body of the function parameter in a higher-order function we inline is very large or if it is not used in multiple places, we should avoid inlining it. Otherwise, it may cause issues during build time.</blockquote><h4>What is the noinline keyword in Kotlin ?</h4><p>If a higher-order function takes multiple functions as parameters, we might not want to inline all of them. In such cases, the noinline keyword comes into play.</p><p>Especially when we need to store a function reference, pass it to another function, assign it to a variable, or use it via reflection, we must mark the corresponding parameter as noinline. Otherwise, the compiler will produce an error because the body of an inlined function is not suitable for such operations.</p><pre>fun main() {<br>    val greet = {<br>        println(&quot;Hello!&quot;)<br>    }<br><br>    val bye = {<br>        println(&quot;Goodbye!&quot;)<br>    }<br><br>    helloAndGoodbye(greet, bye)<br>}<br><br>inline fun helloAndGoodbye(<br>    action1: () -&gt; Unit,<br>    noinline action2: () -&gt; Unit<br>) {<br>    action1()<br>    val ref = action2 // assigning to a variable requires noinline<br>    ref()<br>}</pre><h4>What is a Non-Local Return?</h4><p>Normally, the return statement is used to exit the function in which it is written. However, when used inside a lambda expression within an inline function, the return does not just exit the lambda itself—it also exits the outer function that called the lambda. This behavior is known as a <strong>non-local return</strong>.</p><pre>fun main() {<br>    println(&quot;Start&quot;)<br>    val numbList = listOf(10, 20, 30, 40, 50)<br>    numbList.forEach {<br>        if (it == 30) {<br>            return<br>        }<br>        println(it)<br>    }<br>    println(&quot;End&quot;)<br>}<br>// Note: Since forEach is a standard higher-order function in Kotlin, <br>// non-local return comes into play.<br>// OUTPUT: Start 10 20 </pre><h4>What is the crossinline keyword in Kotlin ?</h4><p>The crossinline keyword is a parameter modifier used in inline functions, and its purpose is to prevent the lambda expression passed as a parameter from performing a non-local return.</p><pre>fun main() {<br>    runTask {<br>        println(&quot;Task is running&quot;)<br><br>        // return =&gt; Compiler error: non-local return is forbidden<br>        return@runTask  // only exit from the lambda, compiler allows this<br>    }<br>    println(&quot;main finished&quot;)<br>}<br><br>inline fun runTask(crossinline action: () -&gt; Unit) {<br>    val runnable = Runnable {<br>        println(&quot;Runnable started&quot;)<br>        action()<br>        println(&quot;Runnable finished&quot;)<br>    }<br>    runnable.run()<br>}<br><br>/*<br>OUTPUT:<br>Runnable started<br>Task is running<br>Runnable finished<br>main finished<br>*/</pre><h4><strong>Summary</strong></h4><p>In this article, I walked you through Kotlin’s higher-order functions and lambdas, showing how they help us write cleaner and more flexible code by letting us pass and return functions easily. We looked at practical examples, including built-in functions, and talked about key Kotlin keywords like inline, noinline, and crossinline that affect how our code runs and performs. With these tools in hand, you’ll be able to write Kotlin code that’s not just efficient but also easier to maintain and extend.</p><blockquote><strong>-Topic List<br></strong>Introduction to Higher-Order Functions<br>Converting a Regular Function to a Higher-Order Function<br>Passing Functions as Arguments (Using Lambdas and Function References)<br>Higher-Order Functions that Return Functions<br>Using the it Keyword in Single-Parameter Lambdas<br>Standard Kotlin Library Higher-Order Functions<br>Performance Considerations in Higher-Order Functions<br>The inline Keyword in Kotlin<br>Important Notes on When Not to Use inline<br>The noinline Keyword and Its Use Cases<br>Understanding Non-Local Returns<br>The crossinline Keyword and Its Purpose</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dc21d0eec91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RESTful API Geliştirme: ASP.NET Core ile Başlangıç Rehberi]]></title>
            <link>https://medium.com/@omersenturk.dev/net-core-ile-restful-servisler-yazmak-ad%C4%B1m-ad%C4%B1m-rehber-09bf9845bf97?source=rss-80278af9146d------2</link>
            <guid isPermaLink="false">https://medium.com/p/09bf9845bf97</guid>
            <category><![CDATA[net-core-6]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[api-tutorial]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Ömer Şentürk]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 12:30:28 GMT</pubDate>
            <atom:updated>2025-04-13T15:34:11.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FToDNgOVg0jq4_aD" /><figcaption>Photo by <a href="https://unsplash.com/@kvncnls?utm_source=medium&amp;utm_medium=referral">Kevin Canlas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bu rehber, RESTful API geliştirmeyi öğrenmek isteyenler için hazırlanmıştır. Amacım, REST mimarisinin temel prensiplerini açıklayarak, ASP.NET Core ile modern bir API’yi adım adım nasıl oluşturacağınızı net ve anlaşılır bir şekilde göstermek. İlk API’mi yazarken karşılaştığım zorluklardan yola çıkarak, bu süreci sizin için kolaylaştırmaya çalıştım.</p><p><strong>REST Nedir?</strong></p><p>REST (Representational State Transfer), web servisleri tasarlamak için kullanılan bir mimari stildir. HTTP protokolü üzerinden çalışır ve kaynakları (örneğin, bir “ürün” ya da “kullanıcı”) URL’lerle temsil eder. CRUD işlemlerini (Create, Read, Update, Delete) HTTP metodlarıyla gerçekleştirir. REST’in temel prensipleri şunlardır:</p><ul><li><strong>Stateless: </strong>Her istek bağımsızdır; sunucu, istemcinin önceki durumunu saklamaz.</li><li><strong>Client-Server:</strong> İstemci ve sunucu arasında net bir ayrım vardır.</li><li><strong>Cacheable: </strong>Yanıtlar önbelleklenebilir, bu da performansı artırır.</li><li><strong>Uniform Interface: </strong>Standart HTTP metodları ve URL’lerle tutarlı bir arayüz sunulur.</li></ul><p>REST, basitliği ve esnekliği sayesinde modern uygulamalarda yaygın olarak tercih edilir.</p><h4>HTTP Metodları ve Kullanımları</h4><p>RESTful API’lerde sıkça kullanılan HTTP metodları:</p><ul><li><strong>GET: </strong>Bir kaynağı okumak için kullanılır. Aynı isteği tekrar yaparsanız aynı sonucu alırsınız (idempotent).</li><li><strong>POST:</strong> Yeni bir kaynak oluşturmak için kullanılır. Her çağrıda yeni bir kayıt yaratır, yani idempotent değildir.</li><li><strong>PUT:</strong> Var olan bir kaynağı tamamen güncellemek için kullanılır. Idempotenttir.</li><li><strong>DELETE:</strong> Bir kaynağı silmek için kullanılır. Idempotenttir.</li></ul><p>Daha az yaygın metodlar:</p><ul><li><strong>PATCH:</strong> Bir kaynağın yalnızca belirli alanlarını günceller.</li><li><strong>HEAD: </strong>GET ile aynı isteği yapar, ancak sadece başlıkları (headers) döndürür.</li><li><strong>OPTIONS: </strong>Sunucunun desteklediği metodları sorgular.</li><li><strong>TRACE </strong>ve<strong> CONNECT</strong> gibi metodlar nadiren kullanılır. Özellikle TRACE, güvenlik riskleri taşıyabileceği için dikkatli olunmalıdır.</li></ul><p>Bu temel bilgilerin ardından, <strong>ASP.NET Core</strong> kullanarak yaygın olarak kullanılan <strong>RESTful</strong> servisleri nasıl yazılabileceğimizi adım adım ele alalım.</p><h4>Proje Kurulumu</h4><p>ASP.NET Core ile bir ürün yönetim API’si geliştirelim. Örnek olarak, bir e-ticaret uygulamasında ürünleri listeleyen, ekleyen, güncelleyen ve silen bir API oluşturacağız.</p><p><strong>Proje Oluşturma</strong></p><p>Visual Studio’da “ASP.NET Core Web API” şablonunu seçin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Kmp7xGkywpDPz_oxq38njA.jpeg" /></figure><p>Kod editörü olarak VS Code kullananlar terminale aşağıdaki kodu yazabilirler.</p><pre>dotnet new webapi -n ProductApi --framework net8.0<br>cd ProductApi</pre><ul><li>-n ile projenin adını belirledik.</li><li>— framework net8.0 ile de hedef projenin .net8.0 ile çalışacağını belirttik.</li></ul><p>Oluşturulan projede varsayılan olarak bir WeatherForecast örneği gelir. Biz kendi API’mizi yazacağımız için bu dosyaları silerek sıfırdan API’mizi yazmaya başlayavağiz.</p><p><strong>Gerekli paketleri yükleyerek devam edelim.</strong></p><pre>dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 8.0.0<br>dotnet add package Swashbuckle.AspNetCore --version 6.6.2</pre><p>Yüklemiş olduğumuz bu paketler API dökümantasyonu ve veri tabanı bağlantısı için gerekli olan paketlerdir. <br><a href="https://www.nuget.org/">https://www.nuget.org/</a> sitesinden tüm paketleri kontrol edebilirsiniz.</p><h4><strong>Modelin Oluşturulması</strong></h4><p>Ürün bilgilerini temsil eden bir <strong>Product</strong> sınıfı tanımlayacağız. Veri doğrulama için anotasyonlar ekleyeceğiz. Bu anotasyonlar DataAnnotations sınıfından türetilir. Benim de başlarda çok yaptığım bir hata olan null reference hatası yüzünden, veri doğrulama kurallarını baştan sıkı tutmalıyız.</p><pre>using System.ComponentModel.DataAnnotations;<br><br>namespace ProductApi.Models<br>{<br>    public class Product<br>    {<br>        public int Id { get; set; }<br><br>        [Required(ErrorMessage = &quot;Ürün adı zorunludur.&quot;)]<br>        [StringLength(100, ErrorMessage = &quot;Ürün adı en fazla 100 karakter olabilir.&quot;)]<br>        public string Name { get; set; } = string.Empty;<br><br>        [StringLength(500, ErrorMessage = &quot;Açıklama en fazla 500 karakter olabilir.&quot;)]<br>        public string? Description { get; set; }<br><br>        [Required(ErrorMessage = &quot;Fiyat zorunludur.&quot;)]<br>        [Range(0.01, double.MaxValue, ErrorMessage = &quot;Fiyat pozitif bir değer olmalıdır.&quot;)]<br>        public decimal Price { get; set; }<br>    }<br>}</pre><ul><li>[Required] : Doldurulmasının zorunlu olan propertylere ekliyerek bu alanların boş bırakılma olasılığını kaldırıyoruz.</li><li>[StringLength] : Ürün adı ve açıklamasına karakter sınırlaması getirdik.</li><li>[Range] : İle birlikte fiyatın negatif olmaması için kontrol ettik.</li></ul><h4>Veritabanı Entegrasyonu</h4><p>Gerçek projelerde veri kalıcılığı için veritabanı şarttır. Bu yüzden bellek yerine SQLite kullanacağız. SQLite kullanmamın sebebi hafif ve kurulumu kolay bir veritabanıdır. Veritabanı işlemlerini yönetmek için Entity Framework Core’u (EF Core) kullanacağız; bu, .NET’te veritabanıyla iletişim kurmayı kolaylaştıran güçlü bir araçtır.</p><p>Bu bölümde, veritabanı bağlantısını yapılandırmak için aşağıdaki adımları izleyeceğiz:</p><ul><li>Projemizde bir Data klasörü oluşturacağız.</li><li>Bu klasör içinde, veritabanı bağlantısını tanımlayan AppDbContext adında bir sınıf oluşturacağız.</li><li>AppDbContext’i projemize entegre edeceğiz.</li></ul><pre>using Microsoft.EntityFrameworkCore;<br><br>namespace ProductApi.Data<br>{<br>    public class AppDbContext : DbContext<br>    {<br>        public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options) { }<br><br>        public DbSet&lt;Product&gt; Products { get; set; }<br>    }<br>}</pre><h3>Program.cs</h3><pre>using Microsoft.EntityFrameworkCore;<br>using ProductApi.Data;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// SQLite bağlantısı<br>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>    options.<br>    UseSqlite(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>// Controller ve Swagger<br>builder.Services.AddControllers();<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>var app = builder.Build();<br><br>// Geliştirme ortamında Swagger<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br>app.UseAuthorization();<br>app.MapControllers();<br><br>app.Run();</pre><h3>appsettings.json</h3><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;Data Source=products.db&quot;<br>  }<br>}</pre><p>Yaptığımız bu işlemler ile birlikte veri tabanı bağlantısı oluşturuldu sıra şablonların oluşturulmasında bunun için terminale aşağıdaki kodları yazmamız gerekli.</p><pre>dotnet ef migrations add InitialCreate<br>dotnet ef database update</pre><h4>Controller Oluşturma</h4><p>Ürün CRUD işlemlerini gerçekleştirecek<strong> ProductsController</strong> sınıfını yazalım. Performans için async/await kullandım. Hata yönetimini ise sizler için kısa ama etkili tutmaya çalıştım.</p><pre>using Microsoft.AspNetCore.Mvc;<br>using Microsoft.EntityFrameworkCore;<br>using ProductApi.Data;<br>using ProductApi.Models;<br><br>namespace ProductApi.Controllers<br>{<br>    [Route(&quot;api/[controller]&quot;)]<br>    [ApiController]<br>    public class ProductsController : ControllerBase<br>    {<br>        //Burda IoC prensibine dayanan Dependency Injection Kullandım.<br>        private readonly AppDbContext _context;<br><br>        public ProductsController(AppDbContext context)<br>        {<br>            _context = context;<br>        }<br><br>        // GET: api/products<br>        [HttpGet]<br>        public async Task&lt;IActionResult&gt; GetProducts()<br>        {<br>            var products = await _context.Products.ToListAsync();<br>            return products.Any() ? Ok(products) : NotFound(&quot;Ürün bulunamadı.&quot;);<br>        }<br><br>        // GET: api/products/5<br>        [HttpGet(&quot;{id}&quot;)]<br>        public async Task&lt;IActionResult&gt; GetProduct(int id)<br>        {<br>            var product = await _context.Products.FindAsync(id);<br>            return product != null ? Ok(product) : NotFound($&quot;ID {id} olan ürün bulunamadı.&quot;);<br>        }<br><br>        // POST: api/products<br>        [HttpPost]<br>        public async Task&lt;IActionResult&gt; CreateProduct([FromBody] Product newProduct)<br>        {<br>            if (!ModelState.IsValid)<br>            {<br>                return BadRequest(ModelState);<br>            }<br><br>            _context.Products.Add(newProduct);<br>            await _context.SaveChangesAsync();<br><br>            return CreatedAtAction(nameof(GetProduct), new { id = newProduct.Id }, newProduct);<br>        }<br><br>        // PUT: api/products/5<br>        [HttpPut(&quot;{id}&quot;)]<br>        public async Task&lt;IActionResult&gt; UpdateProduct(int id, [FromBody] Product updatedProduct)<br>        {<br>            if (!ModelState.IsValid)<br>            {<br>                return BadRequest(ModelState);<br>            }<br><br>            var product = await _context.Products.FindAsync(id);<br>            if (product == null)<br>            {<br>                return NotFound($&quot;ID {id} olan ürün bulunamadı.&quot;);<br>            }<br><br>            product.Name = updatedProduct.Name;<br>            product.Description = updatedProduct.Description;<br>            product.Price = updatedProduct.Price;<br>            <br>            /*<br>       Bu örnekte, güncelleme işlemlerini manuel olarak gerçekleştirdim.<br>       Ancak büyük ölçekli uygulamalarda AutoMapper kütüphanesi sıklıkla <br>       tercih edilir.Nesneler arası dönüşümü otomatikleştirir ve kod tekrarını<br>       azaltır. Daha önce kullanmadıysanız göz atmayı unutmayın :)<br>            */<br><br>            await _context.SaveChangesAsync();<br>            return Ok(product);<br>        }<br><br>        // DELETE: api/products/5<br>        [HttpDelete(&quot;{id}&quot;)]<br>        public async Task&lt;IActionResult&gt; DeleteProduct(int id)<br>        {<br>            var product = await _context.Products.FindAsync(id);<br>            if (product == null)<br>            {<br>                return NotFound($&quot;ID {id} olan ürün bulunamadı.&quot;);<br>            }<br><br>            _context.Products.Remove(product);<br>            await _context.SaveChangesAsync();<br>            return NoContent();<br>        }<br>    }<br>}</pre><p>Yazmış olduğumuz API test etmek için terminale dotnet run yazarak projeyi başlatmamız yeterli olacaktır.</p><pre>dotnet run<br></pre><p>Umarım yazmış olduğum yazıdan faydalanmışsınızdır. İyi çalışmalar :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09bf9845bf97" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>