<?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 Adityamishra on Medium]]></title>
        <description><![CDATA[Stories by Adityamishra on Medium]]></description>
        <link>https://medium.com/@adityamishra2217?source=rss-f000b5f6cd4c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6AGF9bPjfue1jciY</url>
            <title>Stories by Adityamishra on Medium</title>
            <link>https://medium.com/@adityamishra2217?source=rss-f000b5f6cd4c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:13:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adityamishra2217/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[PostgreSQL: From Scratch to Advanced]]></title>
            <link>https://medium.com/@adityamishra2217/postgresql-from-scratch-to-advanced-94967e6290ba?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/94967e6290ba</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[dbms]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Sun, 04 May 2025 05:35:37 GMT</pubDate>
            <atom:updated>2025-05-04T10:19:29.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSjjH6NPcda3rmc6troVAQ.png" /><figcaption>PostgreSQL</figcaption></figure><h3>Introduction</h3><p>Welcome! If you are entirely new to databases and PostgreSQL, this guide is for you. We will start at the very beginning to build a solid foundational understanding of how PostgreSQL works, how it is installed and managed on a Linux system, what roles and privileges mean, and how all these pieces fit together.</p><h3>Databases:</h3><ul><li>A <strong>database</strong> is an organized collection of data, stored and accessed electronically.</li><li>Think of it like a sophisticated spreadsheet: rows and columns, but with powerful querying, transactions, and reliability guarantees.</li></ul><p>Imagine you’re managing your personal finances using Microsoft Excel:</p><ul><li>Each <strong>sheet</strong> is like a <strong>table</strong> in a database.</li><li>The <strong>columns</strong> in the sheet represent different types of information (e.g., “Date”, “Amount”, “Category”).</li><li>Each <strong>row</strong> is one record (e.g., one financial transaction).</li><li><strong>Now imagine Excel could automatically validate data, let multiple people edit it safely at the same time, keep a log of every change, and handle millions of rows — that’s the power of a database!</strong></li></ul><h4>Relational Databases &amp; SQL:</h4><p>In a <strong>relational database</strong>, data is organized into <strong>tables</strong>. Each table has <strong>columns</strong> (fields) and <strong>rows</strong> (records), you use <strong>SQL</strong> (Structured Query Language) to <strong>CREATE</strong>, <strong>READ</strong>, <strong>UPDATE</strong>, and <strong>DELETE</strong> (CRUD) data.</p><ul><li>Common relational systems are: MySQL, Oracle DB, Microsoft SQL Server — and <strong>PostgreSQL</strong> (which we focus here).</li></ul><h4>ACID Properties:</h4><p>Relational databases strive for <strong>ACID</strong> guarantees:</p><ul><li><strong>Atomicity: </strong>A <a href="https://medium.com/@adityamishra2217/postgresql-from-scratch-to-advanced-94967e6290ba#:~:text=What%E2%80%99s%20a%20transaction%3F">transaction</a> is a single package of work. Either the database applies every step in that package, or it applies none. There’s no in‑between. This is Implemented via a <a href="https://www.postgresql.org/docs/current/wal-intro.html">Write–Ahead Log (WAL)</a> and rollback which means before changing data pages, intent is logged, on failure the log drives an automatic undo of partial updates.</li></ul><p>eg: Imagine you’re ordering a pizza with sides and a drink. If the payment for any one item fails, the whole order is canceled — no half‑orders sneak through.</p><ul><li><strong>Consistency: </strong>Every transaction must respect the database’s rules (like “each user must have a unique email,” or “an order can’t reference a non‑existent product”). When you’re done, the data still follows all those rules. This ensures every committed transaction transitions the database from one valid state to another, preserving <strong>integrity constraints</strong> (e.g., primary/foreign keys, unique constraints, check constraints, triggers). Violations are detected at commit time, causing an automatic transaction abort.</li></ul><p>eg: The pizzeria’s system enforces its menu rules. You can’t order a topping that doesn’t exist or pick an invalid combo. Every order must match the menu’s constraints.</p><ul><li><strong>Isolation: </strong>If two people update the database at the same time, neither sees the other’s halfway‑done changes. It’s as if each transaction runs alone, even when they actually overlap. This controls the visibility of concurrent transactions’ intermediate states so each transaction effects appear as if executed serially.</li></ul><p>eg: Even if hundreds of others order at once, you never see their cart updates. Your checkout behaves as if you’re the only customer, so you won’t accidentally add someone else’s extra “soft drink”.</p><ul><li>Durability: Once a transaction is marked “committed,” its changes survive power failures or crashes. The database makes sure those changes are safely stored before saying “OK, done.” This is achieved by flushing <strong>log records</strong> and <strong>modified data pages</strong> to non‑volatile storage before acknowledging commit.</li></ul><p>eg: Once the pizzeria confirms your order, it’s saved — rain or shine, system crash or power flicker — they’ll still make your pizza. Your confirmed order lives on their order board until it’s fulfilled.</p><blockquote><strong>Why it matters:</strong><br> These four guarantees together mean you can trust the database to handle your money transfers, inventory updates, or user sign‑ups without ever ending up in a halfway, broken, or lost state. Just like the pizza example ensures you get exactly what you paid for, ACID properties make sure a database transaction is reliable, consistent, and permanent — even under failure or heavy load.</blockquote><h4>Why PostgreSQL?</h4><ul><li><strong>Open‑Source</strong> and Free: No licensing fees, large community.</li><li><strong>Standards‑Compliant</strong>: Implements most of SQL specifications.</li><li><strong>Reliability</strong>: Used by both startups and enterprises. etc.</li></ul><h3>Operating System Integration on Linux:</h3><h4>System Users vs. Database Roles:</h4><p>When you apt install postgresql, the package creates a Linux user account named <strong>postgres</strong>. This OS user owns the database server processes and data files on disk. <strong>A database role</strong> (or “user”) is an internal concept within PostgreSQL that manages connection permissions and object ownership.</p><p>The Linux user postgres and the database superuser postgres share a name by convention, but live in different &quot;worlds&quot;:</p><ol><li><strong>Linux</strong>: owns files under /var/lib/postgresql/..., runs the server as a systemd service.</li><li><strong>PostgreSQL</strong>: a superuser role, can bypass all checks inside the database.</li></ol><p>Let’s understand this thing in depth first:</p><p>On Linux, every program that runs is owned by some operating‑system user account. When you log in as “john,” your shell and every application you start inherit your user identity (your UID) and run with your permissions. You can read and write files you own, but you cannot touch files owned by other users unless those files are world‑readable or you elevate your rights.</p><p>Some programs are started not by you, but by the system itself at boot time. The PostgreSQL server daemon is one of these: the system’s init service (systemd) launches it automatically under the special OS user account named postgres. That account exists solely to own the database’s files on disk (in /var/lib/postgresql/...) and to isolate the database process from other parts of the system. By running the database under a dedicated OS user, the system ensures that even if the database software were compromised, it could only access the files and resources granted to that one user.</p><p>Inside the database, PostgreSQL maintains its own separate set of users, called <strong>roles</strong>. A role has nothing to do with Linux file permissions; it lives entirely within the database engine and governs what SQL commands you’re allowed to execute, which tables you can read or modify, and what objects you can create or drop. When you connect with a tool like psql, you authenticate as one of these roles.</p><p>The command:</p><pre>sudo -u postgres psql</pre><p>ties these two worlds together. sudo -u postgres tells the Linux kernel “run the following program as the OS user postgres.” Because the psql client then connects over the local Unix socket using PostgreSQL’s default “peer” authentication (discussed later in this blog), the database sees that the connecting OS user is postgres and therefore grants you the database superuser role also named postgres. From that point on you are operating inside PostgreSQL itself, with full superuser privileges at the SQL level—but still under the OS user postgres at the system level.</p><h4>Data Directory and Configuration:</h4><ul><li><strong>Data Directory</strong>: default is /var/lib/postgresql/&lt;version&gt;/main (Debian/Ubuntu). Contains all database files: tables, WAL (write‑ahead log), indexes.</li><li><strong>Configuration Files</strong> (in /etc/postgresql/&lt;version&gt;/main):</li><li>postgresql.conf: tuning parameters (memory, logging, listen addresses, port).</li><li>pg_hba.conf: controls client authentication (which users may connect, from where, and by which methods).</li><li>pg_ident.conf: optional map of OS usernames to database roles.</li></ul><h3>Initializing Your First Cluster:</h3><h4>initdb Explained:</h4><p><strong>initdb</strong> is the command that sets up a fresh &quot;cluster&quot; — a collection of databases under one server instance. On Ubuntu/Debian, this step is automated by the package installer.</p><p>What initdb does:</p><ol><li>Creates the data directory structure.</li><li>Writes default config files (postgresql.conf, pg_hba.conf).</li><li>Initializes system catalogs (special tables PostgreSQL uses to track your objects).</li></ol><h4>Understanding the Cluster:</h4><p>A <strong>PostgreSQL cluster</strong> is not a distributed system here — it’s simply all the databases managed by one server process. You can have multiple clusters (e.g. different versions) on one machine by using different data directories and ports.</p><h3>Starting, Stopping, and Managing the Service:</h3><p>Use <strong>systemd</strong> commands on modern Linux distributions:</p><pre>sudo systemctl start postgresql    # Start the server<br>sudo systemctl status postgresql   # Check if it’s running and view logs<br>sudo systemctl stop postgresql     # Stop gracefully<br>sudo systemctl restart postgresql  # Stop then start<br>sudo systemctl reload postgresql   # Reload configuration without downtime</pre><p><strong>Listen Addresses</strong>: by default PostgreSQL listens only on the local Unix socket. To allow TCP connections, edit listen_addresses in postgresql.conf.</p><p><strong>Port</strong>: default TCP port is 5432. You can change it in postgresql.conf under port = 5432.</p><h3>Connecting with psql:</h3><h4>Invoking psql:</h4><ul><li>As the Linux postgres user:</li></ul><pre>sudo -u postgres psql</pre><p>Switches to OS user postgres and runs the psql client, which by default connects to the postgres database. The prompt shows as postgres=#, indicating you are superuser inside the postgres database.</p><h4>psql Meta‑Commands:</h4><p>A quick reference: (These commands work when you see the prompt similar to postgres=#)</p><ul><li>\l – List all databases.</li><li>\c &lt;dbname&gt; – Connect to database &lt;dbname&gt;.</li><li>\du – List all database roles.</li><li>\dn – List schemas inside current database.</li><li>\dt – List tables in current schema.</li><li>\d &lt;table&gt; – Describe columns, indexes, constraints of &lt;table&gt;.</li><li>\? – Help on psql commands.</li></ul><p>All commands starting with a backslash (\) are specific to psql and are not SQL.</p><h3>Databases, Schemas, and Roles, The Three Pillars:</h3><p>Think of your database system like a big library, and the pieces break down like this:</p><h4>Database:</h4><ul><li>A <strong>database</strong> is a named collection of schemas and objects (tables, indexes, etc.).</li><li>You cannot cross-query from one database to another inside the same session.</li></ul><p><strong>Analogy: D</strong>atabase is like one entire library branch. It contains all its own collections, rooms, catalogs, rules, etc. You can’t wander into another branch (another database) without leaving and “checking in” there.</p><h4>Schemas</h4><ul><li>A <strong>schema</strong> is a namespace inside a database. The default schema is named public.</li><li>Schemas allow logically grouping objects (e.g., analytics, sales, hr)</li></ul><p><strong>Analogy: </strong>A <strong>schema</strong> is like one section or floor in the library (e.g. Fiction, Non‑Fiction, Reference). It’s just a way to <strong>group</strong> related things together so they don’t get mixed up. Most systems give you a default section called public where you start.</p><h4>Roles (Users &amp; Groups)</h4><ul><li>A <strong>role</strong> can be a user (with LOGIN privilege) or a group (without LOGIN).</li><li>Roles can own objects and have privileges granted.</li><li><strong>Superuser</strong> roles bypass all privilege checks</li></ul><p><strong>Analogy: A role</strong> is like a library card that grants you certain rights:</p><ul><li><strong>User‑roles</strong> (with LOGIN) are actual people who can check out books.</li><li><strong>Group‑roles</strong> are like “Staff” or “Researchers” cards — collections of people you can give the same set of rights to.</li><li>Some roles (superusers) are like head librarians: they can roam every section, override rules, and read or change any book.</li></ul><p>Analogies for more topics:</p><h4>Table, A Bookshelf:</h4><ul><li>A <strong>table</strong> is a single bookshelf within a section. On that shelf you keep books that all share the same format — e.g. every book on the shelf is about “Customers,” or every book is about “Orders.”</li></ul><h4>Row &amp; Column, Book and Its Fields:</h4><ul><li>Each <strong>row</strong> is one book on that shelf — one individual record (one customer, one order). Each <strong>column</strong> is a particular attribute of that book — like “Title,” “Author,” “ISBN,” or in database terms “CustomerName,” “SignupDate,” “Email.”</li></ul><h4>Index, The Catalog Card:</h4><ul><li>An <strong>index</strong> is like the little catalog cards you use to find a book faster. Instead of scanning every spine on the shelf, you look in the index and it tells you exactly which shelf (table) and position (row) to go to.</li></ul><h4>The database operations looks similar to these processes:</h4><ul><li>You enter the <strong>library building</strong> (connect to a database).</li><li>You move to the <strong>section</strong> you need (choose a schema).</li><li>You go to the right <strong>bookshelf</strong> (open a table).</li><li>You pull out <strong>books</strong> (rows) and read the <strong>catalog</strong> (index) to find things quickly.</li><li>Your <strong>library card</strong> (role) determines which sections you can enter and which books you can touch.</li></ul><h3>Creating Your Own Database and Role:</h3><h3>Create a Database</h3><p>In psql as superuser:</p><pre>CREATE DATABASE mydb;</pre><p>This creates a new, independent database named mydb. Under the hood, PostgreSQL clones the <strong>template database</strong> template1 ,<strong>template1</strong> is a special database containing the default structure (schemas, extensions, tables, etc.) that each new database inherits. You can customize template1 (for example, by installing extensions or creating utility objects), and those changes will be included in any subsequently created databases. This cloning process ensures your new database starts with a consistent environment matching template1. (usually template1).</p><h4>Creating a role:</h4><pre>CREATE ROLE myrole<br>  WITH LOGIN<br>       PASSWORD &#39;mypwd&#39;<br>       NOSUPERUSER<br>       NOCREATEDB<br>       NOCREATEROLE;</pre><p>Here:</p><ul><li><strong>CREATE ROLE: </strong>Make a new role (a database account).</li><li><strong>myrole</strong>: The name of this role — your application will connect as this.</li><li><strong>WITH LOGIN: </strong>Allows this role to <strong>log in/authenticate</strong> (i.e. open a DB connection).</li><li><strong>PASSWORD ‘…’: </strong>Sets its login password (what it must supply to authenticate) . PostgreSQL <strong>hashes</strong> this behind the scenes.</li><li><strong>NOSUPERUSER: Disables</strong> superuser powers — this role can’t override security or do admin tasks.</li><li><strong>NOCREATEDB: </strong>Prevents it from creating new databases.</li><li><strong>NOCREATEROLE: </strong>Prevents it from creating, altering, or granting other roles.</li></ul><h3>Authentication: pg_hba.conf:</h3><h4>File Location</h4><ul><li>Typically located at: /etc/postgresql/&lt;version&gt;/main/pg_hba.conf in ubuntu.</li></ul><h4>File Purpose and Structure</h4><p>This file controls who can connect to which database, from where, and using what authentication method.</p><p>Each line in pg_hba.conf follows the format:</p><pre># TYPE  DATABASE        USER            ADDRESS                 METHOD</pre><p><strong>Example Entries:</strong></p><pre># Allow local connections using peer authentication<br>local   all             postgres                                peer<br><br># Allow myrole user to connect to mydb database locally with password<br>local   mydb           myrole                             md5<br><br># Allow remote connections from a specific IP range using password authentication<br>host    mydb           myrole     192.168.1.0/24          md5<br><br># Allow all users from local network to connect to all databases using SCRAM<br>host    all             all             10.0.0.0/8              scram-sha-256</pre><h3>Explanation of Columns</h3><p><strong>TYPE</strong>:</p><ul><li>local: Unix-domain socket (for same-machine connections).</li><li>host: TCP/IP.</li><li>hostssl: TCP/IP over SSL.</li><li>hostnossl: TCP/IP without SSL.</li></ul><p><strong>DATABASE</strong>: Name of database(s), or all.</p><p><strong>USER</strong>: Role(s) allowed to connect.</p><p><strong>ADDRESS</strong>: For host types, the IP address range allowed (e.g. 192.168.1.0/24). Ignored for local.</p><p><strong>METHOD</strong>: Authentication method (see below).</p><h4>Authentication Methods</h4><ul><li>trust: No password needed (insecure).</li><li>peer: OS user must match PostgreSQL user (only for local).</li><li>md5: Password encrypted using MD5 hash.</li><li>scram-sha-256: More secure password method.</li></ul><h3>Important Notes and Pitfalls</h3><ul><li><strong>Order matters!</strong> PostgreSQL checks each line from top to bottom and uses the first match.</li><li><strong>Be careful with </strong><strong>trust</strong> — it can expose your database if misused.</li><li>If your changes don’t work, double-check IP addresses, role names, and the method.</li><li><strong>Always reload PostgreSQL</strong> after editing the file:</li></ul><pre>sudo systemctl reload postgresql</pre><ul><li>Or in psql:</li></ul><pre>SELECT pg_reload_conf();</pre><h3>Granting Privileges:</h3><p>Think of privileges as “keys” that let your role do certain things at different “locations” in the database world. We’ll build up from the biggest scope (the whole database) down to individual objects, and then show how to make future objects inherit the same permissions.</p><h4>Database‑Level Privileges:</h4><p><strong>These control what you can do with <em>the entire database</em> named </strong><strong>mydb.</strong></p><pre>GRANT CONNECT   ON DATABASE mydb TO myrole;<br>GRANT TEMPORARY ON DATABASE mydb TO myrole;</pre><p>Now let’s understand what every privilege is, what it means and its analogy:</p><ul><li>CONNECT: Role can open a session/connection to that database.</li></ul><p>Analogy: You have the library’s front‑door key.</p><ul><li>TEMPORARY: Role can create <em>temporary</em> tables in that database session.</li></ul><p>Analogy: You can set up folding tables for a one‑day event inside the library, but they vanish when you leave.</p><p><strong>Why both?</strong></p><ul><li>Without CONNECT, your app can’t even “step inside.”</li><li>Without TEMPORARY, your app can’t use temp tables for caching or intermediate work.</li></ul><h4>Schema‑Level Privileges:</h4><p><strong>Once inside the database, schemas are like sections (e.g. </strong><strong>public). You need rights to walk around and build there.</strong></p><pre>-- First switch into that database (psql example)<br>\c mydb<br><br>GRANT USAGE  ON SCHEMA public TO myrole;<br>GRANT CREATE ON SCHEMA public TO myrole;</pre><p>What each privilege is, what it means:</p><p>USAGE: Role can <em>see</em> and <em>refer</em> to objects (tables, sequences, functions) in that schema.</p><p>CREATE: Role can <em>create</em> new objects (tables, functions) in that schema.</p><ul><li><strong>Sequence of steps:</strong></li></ul><ol><li>CONNECT to the database.</li><li>USAGE lets you run queries that mention public.customers or public.orders.</li><li>CREATE lets you do CREATE TABLE public.logs (…).</li></ol><h4>Object‑Level Privileges:</h4><p><strong>These control what you can do with <em>each</em> table, sequence, or function inside the schema.</strong></p><pre>GRANT ALL PRIVILEGES    ON ALL TABLES    IN SCHEMA public TO mrole;<br>GRANT ALL PRIVILEGES    ON ALL SEQUENCES IN SCHEMA public TO myrole;<br>GRANT EXECUTE           ON ALL FUNCTIONS IN SCHEMA public TO myrole;</pre><h4>Tables</h4><ul><li><strong>ALL PRIVILEGES</strong> = SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER</li><li><strong>SELECT</strong>: read rows</li><li><strong>INSERT</strong>: add new rows</li><li><strong>UPDATE</strong>: change existing rows</li><li><strong>DELETE</strong>: remove rows</li><li><strong>TRUNCATE</strong>: quickly empty the table</li><li><strong>REFERENCES</strong>: use table’s keys in foreign‑key constraints</li><li><strong>TRIGGER</strong>: create triggers on the table</li></ul><blockquote><em>Analogy: You not only can borrow books (SELECT), but also donate new ones (INSERT), correct typos inside books (UPDATE), remove old volumes (DELETE), rearrange by tossing all at once (TRUNCATE), link books to one another (REFERENCES), and attach little sticky‑notes that fire off events (TRIGGER).</em></blockquote><h4>Sequences:</h4><p>Before understanding these privileges let’s first deep dive into sequences:</p><p><strong>What’s a Sequence?</strong></p><p>A <strong>sequence</strong> is simply a database object whose job is to hand out ever‑increasing numbers — one at a time — whenever you ask. You use it most often to generate unique IDs for new rows, like order numbers or invoice IDs.</p><h3>How you use a sequence in SQL</h3><ol><li><strong>Create one:</strong></li></ol><pre>CREATE SEQUENCE invoice_id_seq<br>  START 1        -- begin at 1<br>  INCREMENT 1;   -- go up by 1 each time</pre><p>2 Get the next number:</p><pre>SELECT nextval(&#39;invoice_id_seq&#39;);  <br>-- returns 1, then next call returns 2, then 3, etc.</pre><p>3. Peek at the current number:</p><pre>SELECT currval(&#39;invoice_id_seq&#39;);  <br>-- shows the last number you received in this session</pre><p>4. Reset or jump:</p><pre>SELECT setval(&#39;invoice_id_seq&#39;, 100);  <br>-- now the next nextval() will give 101</pre><h4>Privileges on sequences</h4><ul><li>ALL PRIVILEGES = USAGE, SELECT, UPDATE</li><li>USAGE → You can call nextval() to <em>take</em> a number.</li><li>SELECT → You can call currval() to <em>see</em> what number was last handed out.</li><li>UPDATE → You can call setval() to <em>reset or jump</em> the counter.</li></ul><p><em>Analogy: A sequence is like a numbered ticket dispenser. These rights let you take a ticket (USAGE), look at the last number called (SELECT), or reset the counter (UPDATE).</em></p><h4>Functions</h4><h4>What’s a Function?</h4><p>A <strong>function</strong> in the database is a little block of code — like a mini‑program — stored in the database itself. You call it by name (just like you call a function in your application code) and it can:Take inputs (parameters)</p><ul><li>Run SQL or procedural logic</li><li>Return a result (a value or a set of rows)</li><li>Optionally make changes to the database</li></ul><p>You create them when you have a piece of logic you’ll need many times, or when you want to keep complex calculations centralized.</p><p>Example:</p><pre>-- Define a function that adds 10% tax<br>CREATE FUNCTION add_tax(price numeric) <br>  RETURNS numeric AS $$<br>BEGIN<br>  RETURN price * 1.10;<br>END;<br>$$ LANGUAGE plpgsql;<br><br>-- Use it:<br>SELECT add_tax(200);  -- returns 220</pre><p><strong>Privilege on functions</strong></p><ul><li><strong>EXECUTE</strong> → Allows you to <em>call</em> (run) the function.</li></ul><blockquote><strong><em>Analogy:</em></strong><em><br> Think of a database function as a coffee machine button:</em></blockquote><blockquote>The button <strong>is</strong> the function (e.g. “Espresso”).</blockquote><blockquote>Pressing it tells the machine to run its internal routine (grind beans, force water through).</blockquote><blockquote><strong>EXECUTE</strong> permission is simply the right to press that button.</blockquote><h4>Bringing it together</h4><p>When you do:</p><pre>GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO mrole;</pre><p>you’re giving your myrole role the rights to <strong>take</strong>, <strong>peek</strong>, and <strong>reset</strong> any of those number‑generators (sequences).</p><p>And</p><pre>GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO myrole;</pre><p>you’re letting it <strong>call</strong> every function you’ve defined there — just like letting your application press the buttons on any “machine” you’ve set up inside the database.</p><h4>Default Privileges for Future Objects:</h4><pre>ALTER DEFAULT PRIVILEGES IN SCHEMA public<br>  GRANT ALL PRIVILEGES ON TABLES    TO myrole;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public<br>  GRANT ALL PRIVILEGES ON SEQUENCES TO myrole;</pre><p>Ensures any new tables/sequences you create later automatically grant the same rights and it remember defaults apply to objects created by the role running the ALTER command.</p><h3>Working with Data: SQL CRUD:</h3><ol><li><strong>INSERT</strong> data:</li></ol><pre>INSERT INTO public.users (name) VALUES (&#39;Alice&#39;) RETURNING id;<br>-- Returns the generated ID, e.g. &quot;id: 1&quot;</pre><p><strong>2. SELECT</strong> data:</p><pre>SELECT id, name FROM public.users;<br>-- Example output:<br>--  id | name<br>-- ----+-------<br>--   1 | Alice</pre><p>3. <strong>UPDATE</strong> rows:</p><pre>UPDATE public.users SET name = &#39;Bob&#39; WHERE id = 1 RETURNING *;<br>-- Example output:<br>--  id | name<br>-- ----+------<br>--   1 | Bob</pre><p>4. <strong>DELETE</strong> rows:</p><pre>DELETE FROM public.users WHERE id = 1 RETURNING *;<br>-- Example output:<br>--  id | name<br>-- ----+------<br>--   1 | Bob</pre><h4><strong>Transactions:</strong></h4><h4>What’s a transaction?</h4><p>A <strong>transaction</strong> is like a little “all‑or‑nothing” box you use to group a series of steps. Either <strong>every</strong> step in the box happens, or <strong>none</strong> of them do. This keeps your data safe and consistent.</p><h4>Analogy: Two Envelopes of Cash:</h4><p>Imagine you have two envelopes labeled <strong>A</strong> and <strong>B</strong>, each with some money inside:</p><ul><li>Envelope A: $500</li><li>Envelope B: $300</li></ul><p>You want to move $100 from A to B. That’s two steps:</p><ol><li>Take $100 out of Envelope A</li><li>Put $100 into Envelope B</li></ol><p>If you only do step 1 (take out from A) and then something goes wrong (you drop the cash, or the power goes out), Envelope A is short $100 and Envelope B never got it — that’s bad!</p><p>So you decide to use a “transaction box”:</p><ol><li><strong>BEGIN</strong> (you close both envelopes inside your transaction box)</li><li><strong>Step 1:</strong> Remove $100 from A (still inside the box)</li><li><strong>Step 2:</strong> Add $100 to B (still inside the box)</li><li><strong>COMMIT</strong> (you open the box and let both changes stick)</li></ol><p>If something goes wrong <strong>before</strong> you commit (say you changed your mind, or spilled coffee), you can do a <strong>ROLLBACK</strong>:</p><ul><li><strong>ROLLBACK</strong> = “never mind, undo everything inside the box” — both envelopes go back to their original amounts.</li></ul><h4>Mapping to SQL:</h4><pre>BEGIN;  <br>  -- Start the transaction box<br><br>UPDATE accounts <br>   SET balance = balance - 100 <br> WHERE id = 1;<br>   -- Step 1: take $100 out of account #1<br><br>UPDATE accounts <br>   SET balance = balance + 100 <br> WHERE id = 2;<br>   -- Step 2: add $100 into account #2<br><br>COMMIT;  <br>  -- If both updates succeeded, make them permanent</pre><ul><li><strong>BEGIN;</strong><br> Tells the database: “Start grouping my next commands into one atomic transaction.”</li><li><strong>COMMIT;</strong><br> Tells the database: “Everything in that group worked — go ahead and save it all.”</li><li><strong>ROLLBACK;</strong><br> (If you call this instead of COMMIT) tells the database: “Something went wrong — undo every change in that group. Leave the data exactly as it was before the BEGIN.”</li></ul><h4>System Catalogs (pg_catalog)</h4><p>PostgreSQL has internal tables like pg_class, pg_attribute, pg_roles. Use them if you need deep introspection.</p><h3><strong>Official Documentation</strong>:</h3><ul><li><a href="https://www.postgresql.org/docs/current/">https://www.postgresql.org/docs/current/</a></li><li><a href="https://www.postgresql.org/docs/current/psql.html">https://www.postgresql.org/docs/current/psql.html</a></li></ul><p>Congratulations on getting a bird’s‑eye view of PostgreSQL! With this knowledge, you can not only run and connect to a database but also secure it properly, grant just the right privileges, and understand what happens behind the scenes at each step. Happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94967e6290ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Annotation Processors & Kotlin KAPT: A Deep Dive]]></title>
            <link>https://medium.com/@adityamishra2217/java-annotation-processors-kotlin-kapt-a-deep-dive-105ff147f855?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/105ff147f855</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kapt]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[annotation-processor]]></category>
            <category><![CDATA[annotations]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 11:34:40 GMT</pubDate>
            <atom:updated>2025-04-27T12:44:20.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ud8gTqG168uY8rn3UxnZA.png" /></figure><p>Annotation processors transform your codebase behind the scenes. They scan for annotations at compile time, generate new code or resources, and even enforce coding rules before you ever run your application. When working solely in Java, they hook into javac seamlessly. But introduce Kotlin into the mix, and you need Kotlin’s KAPT tool, which bridges the gap between Kotlin code and the Java annotation-processing API. Misconfiguration is easy—and can silently break features like Spring Bean discovery.</p><p>Below, we’ll journey through annotation processing step by step, starting with how it works in Java, moving into Gradle integration, explaining Kotlin’s KAPT mechanism, and finally exploring a real-world Spring Boot bean-discovery issue in a mixed Java-Kotlin project.</p><h3>From Java to Generated Code</h3><p>Imagine you have a custom annotation @GenerateBuilder. You apply it to a class:</p><pre>@GenerateBuilder<br>public class Person {<br>    private final String name;<br>    private final int age;<br>    // constructor, getters omitted<br>}</pre><p>On its own, this annotation does nothing at runtime. But an annotation processor — packaged in its own JAR — scans your source during compilation and writes a new PersonBuilder class for you. Under the hood, the Java compiler looks for any JAR on its processor path containing a file named META-INF/services/javax.annotation.processing.Processor. That file lists fully qualified processor classes implementing javax.annotation.processing.Processor (typically by extending AbstractProcessor).</p><p>When javac runs, it discovers your processor, calls its init(ProcessingEnvironment) once, then repeatedly calls process(...) in “rounds.” In each round, you examine the RoundEnvironment for elements annotated with @GenerateBuilder. You use ProcessingEnvironment.getFiler() to create new source files. Once all rounds finish—either because no new files appeared or you signal you’ve claimed the annotations—compilation proceeds to generate bytecode for both your handwritten and generated classes.</p><p>A minimal annotation processor looks like this:</p><pre>@SupportedAnnotationTypes(&quot;com.example.GenerateBuilder&quot;)<br>@SupportedSourceVersion(SourceVersion.RELEASE_17)<br>public class BuilderProcessor extends AbstractProcessor {<br>  @Override<br>  public boolean process(Set&lt;? extends TypeElement&gt; annotations,<br>                         RoundEnvironment roundEnv) {<br>    for (Element e : roundEnv.getElementsAnnotatedWith(GenerateBuilder.class)) {<br>      // build class name and package<br>      // open a JavaFileObject via filer<br>      // write builder code<br>    }<br>    return true;<br>  }<br>}</pre><p>You compile this into a JAR alongside a META-INF/services/... entry so that javac can find it.</p><h3>Wiring Processors into Gradle (Java)</h3><p>In a plain Java Gradle project, you tell Gradle which dependencies supply annotation definitions (the interfaces your code refers to) and which supply processor implementations. That is done via three configurations:</p><ul><li>compileOnly for annotations you reference at compile time but don’t include at runtime.</li><li>implementation for libraries you need at both compile and runtime.</li><li>annotationProcessor for JARs containing your Processor classes.</li></ul><pre>plugins { id &#39;java&#39; }<br><br>dependencies {<br>  compileOnly &#39;com.example:annotations:1.0&#39;   // @GenerateBuilder<br>  annotationProcessor &#39;com.example:processor:1.0&#39;<br>  implementation &#39;com.example:annotations:1.0&#39;<br>}</pre><p>When you run ./gradlew compileJava, Gradle feeds the annotationProcessor classpath to javac with the -processorpath option. Any generated sources show up by default under build/generated/sources/annotationProcessor/java/main. Your IDE should mark that directory as a source root so you can navigate into generated code.</p><p>If you distribute a library that consumers will use, they similarly add your processor JAR under annotationProcessor in their build, and you can ship precompiled processors and annotation definitions separately.</p><h3>Enter Kotlin: How KAPT Works</h3><p>Kotlin’s compiler doesn’t natively implement JSR-269. Instead, the Kotlin KAPT plugin performs a two-step dance:</p><p><strong>Stub Generation</strong>: KAPT examines your Kotlin .kt files and emits lightweight Java stubs capturing class names, package declarations, annotation metadata, and method signatures. These stubs live under build/tmp/kaptStubs/....</p><p><strong>Processor Invocation</strong>: Kotlin hands those stubs to the standard Java annotation processors you declared under the kapt configuration. Processors run exactly as if you were compiling Java, creating sources or resources.</p><p><strong>Integration</strong>: Any output from processors is placed under build/generated/source/kapt/main, and then Kotlin compiles both your original .kt files and the newly generated Java sources to produce bytecode.</p><p>In build.gradle, you might see:</p><pre>plugins {<br>  id &#39;org.jetbrains.kotlin.jvm&#39; version &#39;1.9.25&#39;<br>  id &#39;org.jetbrains.kotlin.kapt&#39;<br>}<br><br>dependencies {<br>  compileOnly &#39;com.example:annotations:1.0&#39;<br>  kapt        &#39;com.example:processor:1.0&#39;<br>}<br><br>kapt {<br>  keepJavacAnnotationProcessors = true<br>}</pre><p>The keepJavacAnnotationProcessors flag ensures that if you also have Java sources in the same module using annotationProcessor, they still run. By default, KAPT temporarily disables the Java compile task’s processors to avoid duplicating work on the stubs and real sources.</p><h3>A Mixed Java + Kotlin Codebase</h3><p>In many projects you’ll have some legacy Java and new Kotlin side by side. Gradle treats them as two separate tasks:</p><p>compileJava runs on .java files with annotationProcessor.</p><p>compileKotlin (via KAPT) runs on .kt stubs with kapt.</p><p>If you supply a single shared processor only under annotationProcessor, it will see Java code but not Kotlin stubs. If you put it only under kapt, it will process the stubs but not real Java files. The remedy is to declare it twice:</p><pre>dependencies {<br>  compileOnly &#39;com.example:shared-annotations:1.0&#39;<br>  annotationProcessor &#39;com.example:shared-processor:1.0&#39;<br>  kapt                &#39;com.example:shared-processor:1.0&#39;<br>}<br><br>kapt {<br>  keepJavacAnnotationProcessors = true<br>}</pre><p>That way, your shared processor handles both Java and Kotlin classes, and both generated source directories are merged into your final artifact and IDE source paths.</p><h3>Popular Processors in Action</h3><p><a href="https://projectlombok.org/"><strong>Lombok</strong></a> uses bytecode manipulation rather than source generation. You still declare:</p><pre>compileOnly         &#39;org.projectlombok:lombok:1.18.26&#39;<br>annotationProcessor &#39;org.projectlombok:lombok:1.18.26&#39;</pre><p>and install the Lombok plugin in your IDE for syntax highlighting.</p><p><a href="https://mapstruct.org/"><strong>MapStruct</strong></a> reads mapper interfaces annotated with @Mapper and emits implementation classes. In a mixed project you typically declare it under both configurations because your interfaces can reside in either language.</p><p><strong>Spring Context Indexer</strong> is crucial in Spring Boot. It generates a file META-INF/spring.components listing all your @Component, @Service, and @Repository classes so Spring can skip expensive classpath scanning at startup. You must declare it in both annotationProcessor and kapt to index Java and Kotlin classes alike:</p><pre>annotationProcessor &#39;org.springframework:spring-context-indexer:6.0.6&#39;<br>kapt            &#39;org.springframework:spring-context-indexer:6.0.6&#39;</pre><p><strong>Spring Boot Configuration Processor</strong> generates JSON metadata for your @ConfigurationProperties classes. If those classes are written in Kotlin, kapt alone suffices, for Java classes, you also add it under annotationProcessor.</p><h3>Case Study: Missing Beans in Spring Boot</h3><p>Consider a Spring Boot app with a mix of Java and Kotlin. You refactor your ProjectService from Java to Kotlin and suddenly Spring reports:</p><pre>UnsatisfiedDependencyException: No qualifying bean of type &#39;com.example.ProjectService&#39;</pre><p>Your Kotlin class still carries @Service, and your application’s base package is correct. Yet, the bean is invisible.</p><p>The culprit is the Spring Context Indexer. Initially you had:</p><pre>annotationProcessor &#39;org.springframework:spring-context-indexer:6.0.6&#39;<br>kapt &#39;org.springframework.boot:spring-boot-configuration-processor&#39;</pre><p>With that setup:</p><ol><li><strong>JavaCompile</strong> ran the indexer and wrote META-INF/spring.components with only Java beans.</li><li><strong>KAPT</strong> never saw the indexer on stubs, so Kotlin beans were omitted.</li><li>Spring Boot, detecting a partial index file, skipped classpath scanning and relied solely on that incomplete index.</li></ol><p>To fix it, you add the indexer to both configurations and re-enable JavaCompile processors:</p><pre>dependencies {<br>  annotationProcessor &#39;org.springframework:spring-context-indexer:6.0.6&#39;<br>  kapt            &#39;org.springframework:spring-context-indexer:6.0.6&#39;<br>  kapt            &#39;org.springframework.boot:spring-boot-configuration-processor&#39;<br>}<br><br>kapt {<br>  keepJavacAnnotationProcessors = true<br>}</pre><p>After rebuilding, you can inspect two index files — one under the Java output directory and one under the KAPT stubs directory — both listing your Kotlin ProjectService. Gradle merges them into the final JAR, and Spring successfully wires all beans.</p><h3>More Info:</h3><p>For in-depth explanation of java annotation processors and how they works under the hood, I’d recommend this video by <strong>Tom Gregory</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEMdavUDRmy4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEMdavUDRmy4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEMdavUDRmy4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/91a97e5f1d5c479bce9d5a13f5da2472/href">https://medium.com/media/91a97e5f1d5c479bce9d5a13f5da2472/href</a></iframe><p>Alternatively you may refer this article:</p><p><a href="https://www.baeldung.com/java-annotation-processing-builder">https://www.baeldung.com/java-annotation-processing-builder</a></p><ul><li>For a deep dive in the case study of mixed kotlin-java spring boot project, see this Stack Overflow question and the accepted answer:</li></ul><p><a href="https://stackoverflow.com/questions/79316031/spring-boot-autowiring-fails-for-kotlin-service-and-repository-classes-in-a-mixe">Spring Boot Autowiring Fails for Kotlin Service and Repository Classes in a Mixed Java-Kotlin Application</a></p><ul><li>Additional items for understanding this:</li><li>&gt; Repository: <a href="https://github.com/this-Aditya/SpringErrorReproducing">https://github.com/this-Aditya/SpringErrorReproducing</a></li><li>&gt; How to reproduce issue: <a href="https://github.com/this-Aditya/SpringErrorReproducing/blob/main/README.md">https://github.com/this-Aditya/SpringErrorReproducing/blob/main/README.md</a></li><li>&gt; Pull Requests for resolving errors: <a href="https://github.com/this-Aditya/SpringErrorReproducing/pulls?q=is%3Apr+is%3Aclosed">https://github.com/this-Aditya/SpringErrorReproducing/pulls?q=is%3Apr+is%3Aclosed</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=105ff147f855" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding IP Addresses, CIDR, VPCs, and Network Components]]></title>
            <link>https://medium.com/@adityamishra2217/understanding-ip-addresses-cidr-vpcs-and-network-components-9fde02c7dc14?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fde02c7dc14</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[ip-address]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 11:23:13 GMT</pubDate>
            <atom:updated>2025-02-24T11:23:13.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9phOI2kbliOkB4v_DbhYmw.jpeg" /></figure><p>In today’s interconnected world, understanding the basics of networking is essential — whether you’re setting up a home Wi-Fi network, diving into cloud computing with AWS, or simply curious about how your mobile device connects to the internet. This blog post brings together key concepts from IP addresses and CIDR notation to Virtual Private Clouds (VPCs) and the roles of modems, routers, firewalls, and NAT.</p><h3>What Is an IP Address?</h3><p>An <a href="https://en.wikipedia.org/wiki/IP_address"><strong>IP address</strong></a> is a unique numerical label assigned to every device that communicates over a network using the Internet Protocol. Think of it as a phone number for your computer, smartphone, or any connected device. There are two major versions in use today:</p><ul><li><strong>IPv4:</strong> Uses a 32-bit numeric format (e.g: 192.168.1.1) and offers about 4 billion possible addresses.</li><li><strong>IPv6:</strong> Uses a 128-bit numeric format (e.g: 2001:0db8:85a3:0000:0000:8a2e:0370:7334), supporting an exponentially larger number of addresses.</li></ul><h3>Public vs. Private IP Addresses</h3><ul><li><strong>Public IP Addresses:</strong><br>These addresses are globally unique and are assigned by Internet authorities. Any device that needs to be accessed over the internet (like a web server) will have a public IP. No two devices on the public internet can share the same public IP address.</li><li><strong>Private IP Addresses:</strong><br>Reserved for use within local networks (homes, offices, or cloud environments), private IP addresses are not reachable from the public internet. Ranges defined by <a href="https://datatracker.ietf.org/doc/html/rfc1918">RFC 1918</a> include:</li><li><strong>10.0.0.0/8</strong> (10.0.0.0 to 10.255.255.255)</li><li><strong>172.16.0.0/12</strong> (172.16.0.0 to 172.31.255.255)</li><li><strong>192.168.0.0/16</strong> (192.168.0.0 to 192.168.255.255)</li></ul><p>Private IP addresses can be reused across different networks because each network is isolated — making them an efficient solution for local addressing.</p><h3>What Is CIDR?</h3><p><a href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing"><strong>CIDR (Classless Inter-Domain Routing)</strong></a> is a method to denote IP address ranges more efficiently than the traditional class-based system.</p><p>Consider the CIDR block: <strong>172.31.0.0/16</strong>. Here’s what it means:</p><ul><li><strong>IP Portion (172.31.0.0):</strong><br>This is the starting address of the block.</li><li><strong>Suffix (/16):</strong><br>The “/16” indicates that the first 16 bits of the IP address are fixed, leaving the remaining 16 bits available for host addresses. This provides a range from 172.31.0.0 up to 172.31.255.255, allowing for 65,536 unique addresses within that block.</li></ul><p>CIDR makes it straightforward to split a large network into smaller sub-networks (subnets) and efficiently manage IP address allocation.</p><h3>What Is a VPC?</h3><blockquote><strong>NOTE: </strong>The VPC is specifically discussed in detail when we learn cloud computing, it’s okay if you are unfamiliar with cloud computing and you face difficulty in understanding this. You may skip this.</blockquote><p>A <a href="https://en.wikipedia.org/wiki/Virtual_private_cloud"><strong>Virtual Private Cloud (VPC)</strong></a> is an isolated, customizable network environment within a cloud provider’s infrastructure (<a href="https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html">like AWS</a>). Imagine it as your private data center in the cloud where you control the entire network setup.</p><h3>Features of a VPC:</h3><ul><li><strong>Isolation:</strong><br>Your VPC is logically separated from other customers’ networks, ensuring security and control.</li><li><strong>Customizable IP Range:</strong><br>You define the VPC’s CIDR block (for example, 172.31.0.0/16), determining the range of private IP addresses available for your cloud resources.</li><li><strong>Subnets:</strong><br>Within a VPC, you can create public subnets (with internet access) and private subnets (isolated from the internet for sensitive resources).</li><li><strong>Routing and Security:</strong><br>VPCs use route tables to manage how traffic flows between subnets and to/from the internet. Rules dictate that traffic destined for the internal network remains within the VPC, while traffic aimed at external networks (matched by a route like 0.0.0.0/0) goes to an Internet Gateway.</li></ul><h3>How NAT, Routers, Firewalls, and Modems Work Together?</h3><h3>A Home Wi-Fi Network Scenario</h3><p>Imagine your home network with a Wi-Fi connection where a laptop, two mobile phones, and a camera are connected. Each device receives a private IP address, but how do they access the internet? Let’s explore the roles of various components:</p><h4>Modem</h4><ul><li><strong>Role:</strong><br>The modem connects your local network to your ISP by converting signals from your ISP (DSL, cable, fiber, etc.) into digital data that your network can understand.</li><li><strong>Function:</strong><br>It typically receives a single public IP address from your ISP and passes the data along to your router.</li></ul><h4>Router</h4><ul><li><strong>Role:</strong><br>The router is the central hub that distributes the internet connection to your devices. It also assigns private IP addresses via <a href="https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol">DHCP (Dynamic Host Configuration Protocol)</a>.</li><li><strong>Key Functions:</strong></li><li><a href="https://en.wikipedia.org/wiki/Network_address_translation"><strong>NAT (Network Address Translation):</strong></a><br>NAT allows multiple devices on your local network to share a single public IP address. When a device sends out data, the router replaces its private IP with the public IP and keeps track of the mapping so that incoming responses can be directed to the correct device.</li><li><strong>Traffic Management:</strong><br>The router routes data between devices on your local network and between your network and the internet.</li></ul><h4>Firewall</h4><ul><li><strong>Role:</strong><br>Often integrated into your router, the firewall monitors incoming and outgoing network traffic based on predefined security rules.</li><li><strong>Function:</strong><br>It blocks unauthorized access from the internet, ensuring that external threats do not reach your private devices.</li></ul><h4>The Communication Process</h4><ol><li><strong>Device Request:</strong><br>Your laptop with a private IP (e.g., 192.168.1.10) sends a request to load a webpage.</li><li><strong>NAT in Action:</strong><br>The router intercepts this request, replaces the source address with its public IP, and records the mapping.</li><li><strong>Internet Communication:</strong><br>The request travels to the destination server on the internet.</li><li><strong>Response Handling:</strong><br>The server’s response is sent to the public IP, the router then uses the mapping to forward the response back to the laptop.</li></ol><h3>Cellular Networks: How Do Mobile Phones Connect?</h3><p>Mobile devices connected via cellular towers follow a similar principle but with a few differences.</p><h3>Cellular Data and IP Addressing</h3><ul><li><strong>Connection Mechanism:</strong><br>Your smartphone connects to nearby cellular towers, which are part of your carrier’s network infrastructure.</li><li><strong>IP Assignment:</strong></li><li><strong>Private IPs with CGNAT:</strong><br>Typically, smartphones on cellular networks receive private IP addresses, and carriers use <a href="https://en.wikipedia.org/wiki/Carrier-grade_NAT"><strong>Carrier-Grade NAT (CGNAT)</strong></a> to translate these to a public IP address for internet communication.</li><li><strong>Occasional Public IPs:</strong><br>In some cases, especially with IPv6 or specific network configurations, smartphones might receive a public IP address directly.</li></ul><h3>Communication Over Cellular Networks</h3><ol><li><strong>Device Request:</strong><br>Your smartphone sends out data (for instance, loading a webpage) using its assigned private IP.</li><li><strong>CGNAT Translation:</strong><br>The carrier’s NAT device translates the private IP to a public IP, allowing the request to travel over the internet.</li><li><strong>Response Routing:</strong><br>Responses to the request are routed back to the carrier’s NAT, which then forwards them to your smartphone.</li></ol><h3>Bringing It All Together</h3><h3>Public vs. Private IP Addresses</h3><ul><li><strong>Public IPs:</strong><br>Unique across the internet and used for direct communication on the global network.</li><li><strong>Private IPs:</strong><br>Reserved for internal network communication; reusable in different isolated networks and hidden from the public internet.</li></ul><h3>CIDR Notation</h3><ul><li><strong>Efficient Address Management:</strong><br>CIDR (e.g., 172.31.0.0/16) allows you to define a range of IP addresses, making it easy to allocate and subdivide networks.</li><li><strong>Flexibility:</strong><br>It supports creating subnets that can be isolated or connected as needed in both home and cloud environments.</li></ul><h3>VPCs and Cloud Networking</h3><ul><li><strong>Virtual Private Clouds:</strong><br>VPCs allow you to create isolated, customizable networks in the cloud, with full control over IP ranges, subnets, and routing.</li><li><strong>Internal vs. External Traffic:</strong><br>Route tables in a VPC ensure that internal traffic (using your VPC’s CIDR block) stays within the private network, while a default route (0.0.0.0/0) manages external communication via an Internet Gateway.</li></ul><h3>Home and Cellular Network Components</h3><ul><li><strong>Modems, Routers, and Firewalls:</strong><br>These components work together to convert ISP signals, assign private IPs, perform NAT, and secure your network.</li><li><strong>Cellular Networks:</strong><br>Cellular devices commonly use private IP addressing with CGNAT to facilitate internet access while managing the scarcity of IPv4 addresses.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fde02c7dc14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Concurrency in Kotlin: A Story-Based Explanation]]></title>
            <link>https://medium.com/@adityamishra2217/structured-concurrency-in-kotlin-a-story-based-explanation-058dbffa734a?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/058dbffa734a</guid>
            <category><![CDATA[structured-concurrency]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 11:39:49 GMT</pubDate>
            <atom:updated>2024-11-25T11:39:49.500Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re organizing a <strong>team project</strong>. You’re the team leader, and you divide tasks among your team members. Some tasks are simple, some are complex, and some depend on others. Now, as a responsible leader, you make sure:</p><ol><li>All team members complete their tasks before you declare the project done.</li><li>If a task fails, you know exactly what went wrong and how to handle it.</li><li>No team member keeps working after you decide to cancel the project.</li></ol><p>This analogy represents <strong>structured concurrency</strong> in Kotlin. Let’s explore it step by step.</p><h3>1. The Team: CoroutineScope</h3><p>In Kotlin, a <strong>CoroutineScope</strong> is like your team. It defines a boundary or workspace where all tasks (coroutines) operate. As the leader, you assign tasks to your team, and they’re all tied to this workspace.</p><ul><li>When the scope ends, all tasks in it are canceled.</li><li>You can group related tasks together to ensure they’re completed or stopped as a unit.</li></ul><p><strong>Example: Managing a Team (CoroutineScope)</strong></p><pre>suspend fun main() = coroutineScope { // You’re the team leader here.<br>    launch { // Task 1<br>        println(&quot;Task 1 started&quot;)<br>        delay(500) // Simulating work<br>        println(&quot;Task 1 finished&quot;)<br>    }<br><br>    launch { // Task 2<br>        println(&quot;Task 2 started&quot;)<br>        delay(300) // Simulating work<br>        println(&quot;Task 2 finished&quot;)<br>    }<br><br>    println(&quot;Waiting for all tasks to finish...&quot;)<br>}</pre><p><strong>What Happens?</strong></p><ul><li>You, the leader, wait (coroutineScope) for all tasks to finish before declaring the work done.</li><li>If you quit early (cancel the scope), all tasks stop immediately.</li></ul><h3>2. The Project Plan: Parent-Child Relationship</h3><p>Each task you assign is tied to you, the leader. If you decide to stop the project, all tasks under you are stopped too.</p><p>Imagine this: One of your team members, Alice, assigns a subtask to Bob. If Alice decides to leave (cancel), Bob also stops working because Alice was managing him. This is the <strong>parent-child relationship</strong>.</p><p><strong>Example: Parent-Child Relationship</strong></p><pre>fun main() = runBlocking {<br>    val parentJob = launch { // Parent Task<br>        println(&quot;Parent Task started&quot;)<br>        launch { // Child Task<br>            println(&quot;Child Task started&quot;)<br>            delay(1000) // Simulating work<br>            println(&quot;Child Task finished&quot;)<br>        }<br>        delay(500)<br>        println(&quot;Parent Task finished&quot;)<br>    }<br><br>    delay(300) // Give them some time<br>    println(&quot;Cancelling Parent Task&quot;)<br>    parentJob.cancelAndJoin() // Cancel parent and wait for cleanup<br>    println(&quot;All done&quot;)<br>}</pre><p><strong>What Happens?</strong></p><ul><li>When the “parentJob” cancels, all its children are automatically canceled.</li><li>This prevents tasks from running aimlessly without a purpose.</li></ul><h3>3. Handling Failures: Exception Propagation</h3><p>Imagine one of your team members encounters a critical issue that stops their task. If this issue is serious enough, it’s reported to you, the leader, and the entire project might halt.</p><p>This is how exceptions work in structured concurrency: If a child coroutine fails, the exception propagates to its parent, and the entire scope might cancel unless handled properly.</p><p><strong>Example: Failure Propagation</strong></p><pre>fun main() = runBlocking {<br>    val job = launch {<br>        launch {<br>            println(&quot;Task A started&quot;)<br>            delay(100)<br>            throw Exception(&quot;Task A failed!&quot;) // A failure occurs here<br>        }<br><br>        launch {<br>            println(&quot;Task B started&quot;)<br>            delay(200)<br>            println(&quot;Task B finished&quot;)<br>        }<br>    }<br><br>    try {<br>        job.join() // Wait for all tasks<br>    } catch (e: Exception) {<br>        println(&quot;Caught exception: ${e.message}&quot;)<br>    }<br>}</pre><p><strong>What Happens?</strong></p><ul><li>Task A fails and the exception is propagated to its parent.</li><li>Task B is canceled because Task A’s failure stops the entire parent job.</li></ul><h3>4. Delegating Responsibility: SupervisorScope</h3><p>Now imagine you trust your team to work independently. If one member fails, the others can continue their work. You only step in when the project as a whole is at risk.</p><p>This is <strong>supervisorScope</strong>: It allows child coroutines to handle their own failures without affecting their siblings.</p><p><strong>Example: Independent Team Members</strong></p><pre>fun main() = runBlocking {<br>    supervisorScope {<br>        launch {<br>            println(&quot;Task 1 started&quot;)<br>            delay(100)<br>            throw Exception(&quot;Task 1 failed!&quot;)<br>        }<br><br>        launch {<br>            println(&quot;Task 2 started&quot;)<br>            delay(200)<br>            println(&quot;Task 2 finished&quot;)<br>        }<br>    }<br><br>    println(&quot;All tasks complete, regardless of individual failures&quot;)<br>}</pre><p><strong>What Happens?</strong></p><ul><li>Task 1 fails, but Task 2 completes successfully because the supervisor allows siblings to continue independently.</li></ul><h3>5. Enforcing Deadlines: Timeouts</h3><p>Imagine your project has a strict deadline. If the tasks aren’t completed within the time, you cancel the entire project.</p><p>In Kotlin, you can enforce deadlines using withTimeout or withTimeoutOrNull.</p><p><strong>Example: Setting a Deadline</strong></p><pre>fun main() = runBlocking {<br>    try {<br>        withTimeout(300) { // Enforce a 300ms deadline<br>            repeat(5) { i -&gt;<br>                println(&quot;Task $i started&quot;)<br>                delay(100) // Simulate work<br>            }<br>        }<br>    } catch (e: TimeoutCancellationException) {<br>        println(&quot;Timeout reached! Tasks canceled.&quot;)<br>    }<br>}</pre><p><strong>What Happens?</strong></p><ul><li>If the work takes longer than 300ms, the scope cancels all tasks immediately.</li></ul><h3>6. Combining Everything</h3><p>Let’s combine what we’ve learned into a real-world example. Suppose you’re developing an Android app that loads data from multiple sources (network, database, cache). You want to:</p><ol><li>Load all data sources concurrently.</li><li>Stop all work if the network request fails.</li><li>Set a timeout for the entire operation.</li></ol><p><strong>Example: Loading Data Concurrently</strong></p><pre>fun loadData() = runBlocking {<br>    try {<br>        withTimeout(1000) { // 1-second timeout for the whole operation<br>            val networkData = async { fetchNetworkData() }<br>            val databaseData = async { fetchDatabaseData() }<br>            val cacheData = async { fetchCacheData() }<br><br>            println(&quot;Combined data: ${networkData.await()} + ${databaseData.await()} + ${cacheData.await()}&quot;)<br>        }<br>    } catch (e: Exception) {<br>        println(&quot;Failed to load data: ${e.message}&quot;)<br>    }<br>}<br><br>suspend fun fetchNetworkData(): String {<br>    delay(300) // Simulate network delay<br>    return &quot;Network Data&quot;<br>}<br><br>suspend fun fetchDatabaseData(): String {<br>    delay(200) // Simulate database delay<br>    return &quot;Database Data&quot;<br>}<br><br>suspend fun fetchCacheData(): String {<br>    delay(100) // Simulate cache delay<br>    return &quot;Cache Data&quot;<br>}</pre><p><strong>What Happens?</strong></p><ul><li>All data sources are fetched concurrently.</li><li>If any task fails or the operation exceeds 1 second, all tasks stop immediately.</li></ul><h3>The Intuition</h3><p>Structured concurrency is like being a responsible team leader:</p><ul><li><strong>Scopes</strong> are your team boundaries.</li><li><strong>Parent-child relationships</strong> ensure tasks don’t outlive their purpose.</li><li><strong>Exception handling</strong> allows you to decide whether to stop or continue based on failures.</li><li><strong>Timeouts</strong> keep your project on schedule.</li><li><strong>SupervisorScope</strong> lets team members work independently.</li></ul><p>By enforcing these rules, structured concurrency makes your coroutines <strong>predictable</strong>, <strong>safe</strong>, and <strong>manageable</strong>, ensuring no task runs amok or leaks into the void.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=058dbffa734a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Mystery of Leading and Trailing Slashes in URLs]]></title>
            <link>https://medium.com/@adityamishra2217/understanding-the-mystery-of-leading-and-trailing-slashes-in-urls-e23c207a6b40?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23c207a6b40</guid>
            <category><![CDATA[url]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 18:47:26 GMT</pubDate>
            <atom:updated>2024-11-24T18:47:26.879Z</atom:updated>
            <content:encoded><![CDATA[<p>URLs (Uniform Resource Locators) are fundamental to how we navigate and interact with the web. Yet, the subtle differences between leading and trailing slashes often lead to confusion, especially when constructing or interpreting relative paths. This blog explains the role of leading and trailing slashes and their impact with real-world examples.</p><h4>The Role of a Trailing Slash</h4><p>A trailing slash / at the end of a URL has historically been used to distinguish between a directory and a file resource.</p><ul><li><strong>Without a Trailing Slash</strong><br>A URL like https://example.com/docs is often treated as a request for a file or resource named docs.</li><li><strong>With a Trailing Slash</strong><br>A URL like https://example.com/docs/ is treated as a directory. It implies that additional resources, such as https://example.com/docs/file.html, are part of this directory.</li></ul><p><strong>Example:</strong></p><p>If your base URL is <a href="https://example.com/docs:">https://example.com/docs:</a></p><ul><li>A relative URL guide.html resolves to https://example.com/guide.html.<br>Why? The absence of a trailing slash makes the browser interpret docs as a file, so it navigates up to <a href="https://example.com/">https://example.com/.</a></li><li>Adding a trailing slash (https://example.com/docs/) changes this behavior. Now, guide.html resolves to <a href="https://example.com/docs/guide.html.">https://example.com/docs/guide.html.</a></li></ul><h4>Leading Slash in Relative Paths</h4><p>The leading slash / in relative URLs determines how paths are resolved relative to the base URL.</p><ul><li><strong>With a Leading Slash</strong><br>A path starting with / is treated as absolute relative to the domain root. For example, /images/logo.png will always resolve to https://example.com/images/logo.png, regardless of the base URL.</li><li><strong>Without a Leading Slash</strong><br>Paths without a leading slash are relative to the current path (the directory or file specified by the base URL).</li></ul><p><strong>Example:</strong></p><p>Given the base URL <a href="https://example.com/docs/:">https://example.com/docs/:</a></p><ul><li>/images/logo.png resolves to <a href="https://example.com/images/logo.png.">https://example.com/images/logo.png.</a></li><li>images/logo.png resolves to <a href="https://example.com/docs/images/logo.png.">https://example.com/docs/images/logo.png.</a></li></ul><h4>Combining Trailing and Leading Slashes</h4><p>Understanding the interplay between trailing and leading slashes helps avoid common pitfalls when constructing relative URLs.</p><ol><li><strong>Relative Path Behavior</strong><br>URLs with a trailing slash maintain their “directory-like” behavior, while those without treat the last segment as a file.</li><li><strong>Absolute vs. Relative Links</strong><br>Absolute links (those starting with /) disregard the base URL path and jump to the domain root. Relative links (without a leading slash) extend the current path.</li></ol><p><strong>Example:</strong></p><p>Base URL: https://example.com/docs/page<br>Relative URL: section/info.html</p><ul><li>If page is treated as a file, the resolved URL is <a href="https://example.com/docs/section/info.html.">https://example.com/docs/section/info.html.</a></li><li>If page/ (with a trailing slash) was used, the resolved URL remains the same because the browser assumes the base path is already directory-like.</li></ul><h4>Practical Implications</h4><ul><li><strong>API Endpoints</strong><br>When constructing API URLs, always clarify whether the base URL ends with a trailing slash. Example:</li><li>Base URL: https://api.example.com/v1<br>Endpoint: users<br>Resolved URL: https://api.example.com/users (incorrect).</li><li>To fix this, ensure either a trailing slash in the base URL (https://api.example.com/v1/) or explicitly include the slash in the relative path (/users).</li><li><strong>SEO and Routing</strong><br>Search engines may treat URLs with and without trailing slashes as different, creating duplicate content issues. Always standardize your URL structure.</li><li><strong>Dynamic Websites</strong><br>Web frameworks often use trailing slashes to indicate a folder structure. Avoid confusion by redirecting URLs consistently (e.g., always append a trailing slash).</li></ul><h4>Best Practices</h4><ol><li><strong>Know Your Base URL</strong><br>Always define whether your base URL includes a trailing slash. This avoids ambiguity in relative path resolution.</li><li><strong>Use Absolute URLs When Needed</strong><br>For critical resources like CSS, JavaScript, or images, prefer absolute paths (starting with /) to prevent broken links.</li><li><strong>Consistent Usage</strong><br>Standardize URL structures (with or without trailing slashes) and configure server-side redirects to enforce this.</li><li><strong>Test Your Paths</strong><br>Verify URL resolutions in both development and production environments to catch issues early.</li></ol><p>By understanding the subtle differences between leading and trailing slashes, you can write more predictable and error-free URL structures. Whether working on static websites, dynamic applications, or APIs, this clarity will save time and prevent unexpected behavior.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23c207a6b40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding callbackFlow vs. suspendCoroutine in Kotlin Coroutines]]></title>
            <link>https://medium.com/@adityamishra2217/understanding-callbackflow-vs-suspendcoroutine-in-kotlin-coroutines-56233999cc75?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/56233999cc75</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 17:13:25 GMT</pubDate>
            <atom:updated>2024-11-18T17:13:25.759Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever tried integrating callback-based APIs with Kotlin Coroutines, you’ve likely stumbled upon two intriguing tools: <strong>suspendCoroutine</strong> and <strong>callbackFlow</strong>. At first glance, they might seem like two sides of the same coin—both deal with callbacks, right? But dig deeper, and you’ll find that they serve fundamentally different purposes.</p><p>Let’s explore the differences between these two coroutine constructs, one callback at a time. 🌟</p><h3>Setting the Stage: Callbacks Meet Coroutines</h3><p>Callbacks have been the lifeblood of asynchronous programming for decades. However, they can get messy — nested callbacks (a.k.a. callback hell), complex error handling, and resource leaks are just a few of their pitfalls. Kotlin Coroutines aim to fix this by allowing you to write asynchronous code as if it were synchronous. This is where suspendCoroutine and callbackFlow step in, acting as translators between callback-based APIs and coroutine-friendly code.</p><p>But here’s the twist: they each excel in different scenarios. Let’s start by understanding their core essence.</p><h3>What is suspendCoroutine?</h3><p>Think of suspendCoroutine as a <strong>bridge</strong> for one-time asynchronous tasks. It transforms a callback-based operation that produces a <strong>single result</strong> into a suspending function.</p><h4>How It Works</h4><ul><li>The coroutine <strong>pauses</strong> execution at suspendCoroutine.</li><li>A <strong>continuation</strong> is created and passed into your block.</li><li>When the callback completes, you use the continuation to resume the coroutine with the result (or an exception).</li></ul><h4>The Analogy</h4><p>Imagine ordering pizza. You place the order (start the task), then wait. The delivery person (callback) brings you the pizza (result) or apologizes for running out of cheese (exception). Once you get the pizza, you can eat (resume execution).</p><h4>Code in Action</h4><p>Let’s say you’re working with a legacy network API:</p><pre>interface NetworkCallback {<br>    fun onSuccess(data: String)<br>    fun onError(error: Throwable)<br>}<br><br>suspend fun fetchData(): String = suspendCoroutine { continuation -&gt;<br>    val callback = object : NetworkCallback {<br>        override fun onSuccess(data: String) {<br>            continuation.resume(data) // Resume coroutine with result<br>        }<br><br>        override fun onError(error: Throwable) {<br>            continuation.resumeWithException(error) // Resume coroutine with exception<br>        }<br>    }<br>    makeNetworkRequest(callback) // Start the network request<br>}</pre><h3>What is callbackFlow?</h3><p>If suspendCoroutine is for single results, callbackFlow is for <strong>continuous streams</strong> of data. It lets you convert APIs that emit values repeatedly into a <strong>cold Flow</strong>.</p><h4>How It Works</h4><ul><li>callbackFlow creates a flow, but the <strong>real action begins only when someone starts collecting</strong>.</li><li>Inside the callbackFlow, you register a callback and start emitting values to the flow.</li><li>When the flow is canceled, you clean up with awaitClose.</li></ul><h4>The Analogy</h4><p>Now, imagine you’re live-streaming a cricket match. Every time something exciting happens, the commentator (callback) delivers updates. These updates keep coming as long as you’re watching (collecting). If you turn off the TV (cancel the flow), the broadcaster stops sending updates.</p><h4>Code in Action</h4><p>Here’s how you’d use callbackFlow to observe location updates from a GPS API:</p><pre>interface LocationCallback {<br>    fun onLocationChanged(location: String)<br>    fun onError(error: Throwable)<br>}<br><br>fun observeLocationUpdates(): Flow&lt;String&gt; = callbackFlow {<br>    val callback = object : LocationCallback {<br>        override fun onLocationChanged(location: String) {<br>            trySend(location) // Emit new location<br>        }<br><br>        override fun onError(error: Throwable) {<br>            close(error) // Close the flow with an error<br>        }<br>    }<br><br>    startListeningToLocationUpdates(callback) // Register the callback<br><br>    awaitClose {<br>        stopListeningToLocationUpdates(callback) // Clean up when flow is canceled<br>    }<br>}</pre><h3>When Should You Use suspendCoroutine?</h3><p>Use suspendCoroutine when:</p><ol><li>You’re working with <strong>one-time results</strong>.</li><li>The API triggers its callback <strong>exactly once</strong>.</li><li>You want to integrate such an API into a coroutine’s suspendable flow.</li></ol><h4>Real-Life Example</h4><p>Fetching user details via a callback-based API:</p><pre>suspend fun fetchUserDetails(): UserDetails = suspendCoroutine { continuation -&gt;<br>    val callback = object : UserDetailsCallback {<br>        override fun onSuccess(details: UserDetails) {<br>            continuation.resume(details)<br>        }<br><br>        override fun onError(error: Throwable) {<br>            continuation.resumeWithException(error)<br>        }<br>    }<br>    getUserDetailsAsync(callback)<br>}</pre><h3>When Should You Use callbackFlow?</h3><p>Use callbackFlow when:</p><ol><li>You’re working with <strong>continuous data streams</strong>.</li><li>The API triggers callbacks <strong>multiple times</strong> over time.</li><li>You want to emit values as a Flow with lifecycle-aware cancellation.</li></ol><h4>Real-Life Example</h4><p>Listening to Bluetooth connection status:</p><pre>fun observeBluetoothStatus(): Flow&lt;BluetoothStatus&gt; = callbackFlow {<br>    val callback = object : BluetoothStatusCallback {<br>        override fun onStatusChanged(status: BluetoothStatus) {<br>            trySend(status)<br>        }<br>    }<br><br>    registerBluetoothCallback(callback)<br>    <br>    awaitClose {<br>        unregisterBluetoothCallback(callback)<br>    }<br>}</pre><h3>The Key Takeaway</h3><p>The choice between suspendCoroutine and callbackFlow boils down to <strong>quantity</strong>:</p><ul><li><strong>Single event?</strong> Go with suspendCoroutine.</li><li><strong>Multiple events?</strong> Choose callbackFlow.</li></ul><p>While both tools help tame callback chaos, understanding their strengths and limits is the first step to writing cleaner, more efficient Kotlin code.</p><h3>Conclusion</h3><p>By now, you should have a clear understanding of how suspendCoroutine and callbackFlow differ and when to use each. The former simplifies one-off callbacks, while the latter elegantly bridges the gap for continuous streams. Armed with this knowledge, you’re ready to tackle any callback-based API like a Kotlin coroutine pro. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56233999cc75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Preservation and Exception Transparency in Kotlin Flows]]></title>
            <link>https://medium.com/@adityamishra2217/context-preservation-and-exception-transparency-in-kotlin-flows-58b190005b82?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/58b190005b82</guid>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 15:11:28 GMT</pubDate>
            <atom:updated>2024-10-17T15:13:12.047Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Kotlin flows" src="https://cdn-images-1.medium.com/max/1024/1*ZuLzLZ_JyvAbQq94M9Nvpg.jpeg" /></figure><p>Kotlin’s <strong>coroutines</strong> and <strong>flows</strong> offer developers a powerful way to handle asynchronous data streams in a structured and declarative manner. As you dive deeper into flows, you’ll encounter two essential concepts: <strong>Context Preservation</strong> and <strong>Exception Transparency</strong>. These principles help manage execution contexts and exceptions in a flow, ensuring predictable and intuitive behavior across complex asynchronous operations. In this post, we’ll take an in-depth look at both concepts with practical examples to demystify their workings.</p><h3>1. What is Context Preservation in Kotlin Flows?</h3><p>In Kotlin, coroutines are always executed within a <strong>coroutine context</strong> that determines where and how they run. This context could specify a dispatcher (Dispatchers.IO, Dispatchers.Main, etc.) or other coroutine-specific parameters. When working with flows, <strong>context preservation</strong> ensures that the flow encapsulates its execution context and prevents it from being leaked or propagated downstream.</p><h4>What does context preservation mean?</h4><p>Context preservation means that the <strong>upstream flow</strong> (the part of the flow that emits values) runs in its own context and doesn’t affect the <strong>downstream flow</strong> (the part that collects or processes values). The upstream flow always runs in the context where the terminal operation (e.g., collect) is executed unless you explicitly change the upstream context with the flowOn operator.</p><h4>How does flowOn affect context preservation?</h4><p>The only operator that can change the context of a flow is flowOn. It alters the execution context of all upstream operations without affecting downstream ones. This encapsulation makes reasoning about flow execution easier, as you always know what context each part of the flow runs in.</p><p>Let’s see this in action with a simple example.</p><h3>Example: Context Preservation in Action</h3><pre>import kotlinx.coroutines.*<br>import kotlinx.coroutines.flow.*<br><br>fun main() = runBlocking {<br>    // Define a flow that emits numbers and modifies them<br>    val flowA = flowOf(1, 2, 3)<br>        .map { it + 1 }          // Executed in Dispatchers.IO<br>        .flowOn(Dispatchers.IO)   // Switch context to IO for upstream<br><br>    withContext(Dispatchers.Main) {<br>        // Downstream operations like &#39;filter&#39; and &#39;collect&#39; happen in the Main dispatcher<br>        flowA<br>            .filter { it == 3 }<br>            .collect {<br>                println(&quot;Collected $it on thread ${Thread.currentThread().name}&quot;)<br>            }<br>    }<br>}</pre><ul><li><strong>Upstream Context (</strong><strong>Dispatchers.IO):</strong> The map operator runs in the Dispatchers.IO context because of flowOn.</li><li><strong>Downstream Context (</strong><strong>Dispatchers.Main):</strong> The filter and collect operations run on the <strong>Main dispatcher</strong> because we used withContext(Dispatchers.Main) around the collection.</li></ul><p>Here, <strong>context preservation</strong> ensures that each part of the flow runs in its specified context. The upstream encapsulates its context (Dispatchers.IO), and the downstream uses the context of the collect block (Dispatchers.Main).</p><h3>Best Practices for Context Preservation:</h3><ul><li><strong>Use </strong><strong>flowOn</strong> to explicitly control where upstream flow emissions happen, making your flows more predictable and efficient.</li><li><strong>Avoid context switching within a flow</strong> using withContext inside emitters, as it violates the rules of context preservation and can lead to unpredictable behavior.</li><li>If you need to split the emission and collection of values into separate coroutines, use channelFlow, which handles this complexity internally.</li></ul><h3>2. What is Exception Transparency in Kotlin Flows?</h3><p><strong>Exception Transparency</strong> refers to how exceptions are propagated and handled in Kotlin flows to ensure that failures in asynchronous streams are managed predictably. Kotlin flows follow a transparent model where upstream exceptions (those occurring during emission or transformation) and downstream exceptions (those occurring during collection) are handled separately but in a way that’s consistent and predictable.</p><h4>How Exception Transparency Works</h4><p>When working with Kotlin flows, the way exceptions are handled can be tricky, especially when you have both upstream and downstream exceptions.</p><p>The core idea is that <strong>the flow must stop emitting values as soon as an exception is thrown</strong> by either emit or emitAll. When this happens, the flow finishes with an exception, and no more values are emitted.</p><h4>Immediate flow termination</h4><p>If emit or emitAll throws an exception, the flow <strong>immediately stops</strong> emitting new values and finishes with that exception. This ensures that the flow doesn&#39;t continue in an erroneous state.</p><p>However, <strong>the exception that terminates the flow might not always be the one thrown by the emission</strong>. In some cases, the flow may replace the original exception for application-specific purposes, suppressing the original one (more on this below).</p><h4>Handling upstream and downstream exceptions separately</h4><p>Kotlin flows make a clear distinction between <strong>upstream exceptions</strong> and <strong>downstream exceptions</strong>:</p><ul><li><strong>Upstream exceptions</strong>: These are exceptions that occur during the emission or transformation of data (e.g., in emit, map, filter, etc.). They are handled using the catch operator, which is designed to intercept exceptions thrown in the upstream flow and provide a way to recover or handle errors.</li><li><strong>Downstream exceptions</strong>: These are exceptions that occur during terminal operations (e.g., collect, single, toList, etc.). Downstream exceptions are <strong>not caught by the </strong><strong>catch operator</strong>. They propagate outside the flow and must be handled using a try-catch block around the flow collection.</li></ul><p>Let’s see this in action with an example:</p><pre>import kotlinx.coroutines.*<br>import kotlinx.coroutines.flow.*<br><br>fun main() = runBlocking {<br>    try {<br>        flow {<br>            emit(1)<br>            emit(2)<br>            throw Exception(&quot;Upstream failure&quot;) // This is an upstream exception<br>        }<br>        .map { value -&gt;<br>            if (value == 2) throw Exception(&quot;Mapping error&quot;) // Another upstream exception<br>            value<br>        }<br>        .catch { e -&gt;<br>            println(&quot;Caught upstream exception: $e&quot;) // Catches upstream exceptions<br>        }<br>        .collect { value -&gt;<br>            if (value == 1) {<br>                throw Exception(&quot;Downstream failure&quot;) // This is a downstream exception<br>            }<br>            println(value)<br>        }<br>    } catch (e: Exception) {<br>        println(&quot;Caught downstream exception: $e&quot;) // Catches downstream exceptions<br>    }<br>}</pre><h3>Explanation:</h3><ul><li><strong>Upstream exceptions</strong>:</li><li>The flow emits values 1 and 2, but throws an exception (&quot;Upstream failure&quot;) before emitting a third value.</li><li>The map operator also throws an exception (&quot;Mapping error&quot;) when it processes the value 2.</li><li>The catch operator catches both upstream exceptions (&quot;Upstream failure&quot; and &quot;Mapping error&quot;).</li><li><strong>Downstream exceptions</strong>:</li><li>When collecting the value 1, the collect block throws an exception (&quot;Downstream failure&quot;).</li><li>This downstream exception <strong>is not caught</strong> by the catch operator because catch only handles upstream exceptions. Instead, it is caught by the try-catch block outside the flow.</li></ul><p>This shows how exception transparency ensures that <strong>upstream exceptions</strong> are handled inside the flow, while <strong>downstream exceptions</strong> are left to be handled externally.</p><h3>Exception Supersession</h3><p>There is another important behavior related to exception transparency: <strong>exception supersession</strong>.</p><h4>What happens when both upstream and downstream exceptions occur?</h4><p>If both an upstream exception (e.g., during emit or map) and a downstream exception (e.g., during collect) occur at the same time, the <strong>upstream exception</strong> will overtake the downstream one. In other words, the flow will treat the upstream exception as the primary exception, and the downstream exception will be suppressed.</p><pre>flow {<br>    emit(1)<br>    throw Exception(&quot;Emit failure&quot;) // Flow stops here<br>    emit(2) // This won&#39;t be emitted<br>}<br>.catch { e -&gt;<br>    println(&quot;Caught upstream exception: $e&quot;)<br>}<br>.collect { value -&gt;<br>    println(value)<br>}</pre><p><strong>Exception Transparency</strong> in Kotlin flows ensures a predictable and reliable way of handling errors. It distinguishes between upstream and downstream exceptions, ensuring that exceptions in the flow emission and transformation process are handled within the flow, while exceptions in terminal operations like collect must be handled outside the flow.</p><p>This separation makes flows easier to reason about and debug, as you always know where exceptions will be caught and where they need to be handled externally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58b190005b82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding supervisorScope, SupervisorJob, coroutineScope, and Job in Kotlin: A Deep Dive into…]]></title>
            <link>https://medium.com/@adityamishra2217/understanding-supervisorscope-supervisorjob-coroutinescope-and-job-in-kotlin-a-deep-dive-into-bcd0b80f8c6f?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd0b80f8c6f</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 15:30:01 GMT</pubDate>
            <atom:updated>2025-06-22T03:04:26.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding supervisorScope, SupervisorJob, coroutineScope, and Job in Kotlin: A Deep Dive into Failure Propagation and Structured Concurrency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKr7WVnG1tpMl0qvZB-AXg.jpeg" /><figcaption>Coroutine Scope</figcaption></figure><p>Kotlin coroutines provide a powerful and flexible way to handle concurrency. But understanding how coroutines handle errors and manage their lifecycle requires an in-depth look at some key components: supervisorScope, SupervisorJob, coroutineScope, and Job.</p><p>In this article, we&#39;ll unravel the mystery behind these concepts and answer a critical question: Why does SupervisorJob not behave the same as supervisorScope when it comes to handling failures? We’ll also explore why coroutineScope cancels all children when one fails, while supervisorScope isolates the failure to the specific child coroutine.</p><h3>1. Coroutine Basics: Job and Structured Concurrency</h3><p>At the heart of Kotlin coroutines lies the concept of structured concurrency. In structured concurrency, every coroutine is a part of a hierarchy of jobs. These jobs control the lifecycle of coroutines and define how they behave when an exception is thrown or cancellation occurs.</p><p>The simplest construct, Job, is used in most coroutine scopes. A Job:</p><ul><li>Manages the coroutine’s lifecycle (starting, canceling, and completing).</li><li>Can represent a parent coroutine, which is responsible for managing its child coroutines.</li></ul><p>In structured concurrency, if a child coroutine fails, the parent coroutine (and therefore all other children) are typically cancelled. This behavior is observed in a regular Job and the coroutineScope builder.</p><h3>2. coroutineScope: Propagating Failures to All Children</h3><p>The coroutineScope builder is one of the core tools in structured concurrency. When you launch coroutines within a coroutineScope, the failure of any child coroutine results in the <strong>cancellation of the entire scope and all its children</strong>. This strict failure handling ensures that if one part of your operation fails, no other child coroutine continues running in an inconsistent or invalid state.</p><h4>Key Characteristics of coroutineScope:</h4><ul><li>It creates a <strong>parent-child relationship</strong> between the scope and its coroutines.</li><li>When any child coroutine fails (throws an exception), the failure is propagated upward to the parent.</li><li>Once the parent detects a failure, it cancels all remaining coroutines within the scope.</li></ul><h4>Why Does coroutineScope Cancel All Children on Failure?</h4><p>The logic behind coroutineScope&#39;s behavior is straightforward: all children of the scope represent a single unit of work. If one coroutine fails, it compromises the integrity of the entire scope. Cancelling the remaining coroutines ensures that no partial or invalid results are processed. This behavior aligns with Kotlin’s goal of ensuring predictability and consistency in concurrent programming.</p><pre>import kotlinx.coroutines.launch<br>import kotlinx.coroutines.runBlocking<br>import kotlinx.coroutines.coroutineScope<br>import kotlinx.coroutines.delay<br><br>fun main() = runBlocking {<br>    coroutineScope {<br>        launch {<br>            println(&quot;Data 1: ${getData1()}&quot;)<br>        }<br>        launch {<br>            println(&quot;Data 2: ${getData2()}&quot;)<br>        }<br>        launch {<br>            println(&quot;Data 3: ${getData3()}&quot;)<br>        }<br>    }<br>    Unit<br>}<br><br>suspend fun getData1() = delay(1000).run { &quot;data 1&quot; }<br>suspend fun getData2(): Nothing = delay(300).run { throw RuntimeException(&quot;Error in Data 2&quot;) }<br>suspend fun getData3() = delay(800).run { &quot;data 3&quot; }</pre><p>In this case, when getData2() throws an exception, all other coroutines are cancelled before completion, meaning getData1() and getData3() never get printed.</p><h3>3. The Power of SupervisorJob:</h3><p>When you need more granular control over failure handling, the SupervisorJob comes into play. A SupervisorJob allows child coroutines to fail independently of each other. If one child coroutine fails, it does not automatically cancel the other coroutines or the parent scope.</p><p>This is particularly useful when the failure of one operation shouldn’t disrupt others. Think of user interfaces, where one task (e.g., loading an image) failing shouldn’t stop other unrelated tasks (e.g., loading text).</p><h4>Key Characteristics of SupervisorJob:</h4><ul><li>Failure of one child coroutine <strong>does not propagate</strong> to the parent or sibling coroutines.</li><li>The parent job (the SupervisorJob) supervises child coroutines, ensuring that failures are isolated.</li></ul><h4>Where Does SupervisorJob Come Into Play?</h4><p>When you pass SupervisorJob() to a CoroutineScope, that scope becomes a supervisor for its children. This means that each child launched in that scope is isolated from the failure of its siblings.</p><p>However, a critical thing to note is that <strong>SupervisorJob does not automatically handle exceptions inside nested child coroutines</strong>. You need to manually handle exceptions inside each coroutine to prevent failure propagation.</p><pre>fun main() = runBlocking {<br>    val customScope = CoroutineScope(SupervisorJob())<br><br>    customScope.launch {<br>        launch { println(&quot;Data 1: ${getData1()}&quot;) }<br>        launch { println(&quot;Data 2: ${getData2()}&quot;) } // Fails<br>        launch { println(&quot;Data 3: ${getData3()}&quot;) }<br>    }.join()<br>}</pre><p>Here, getData2() fails, but <strong>without additional exception handling</strong>, the failure still propagates upward, potentially affecting the entire customScope. This is because each launch inside customScope is treated as an independent child but follows normal coroutine rules regarding exception propagation. To prevent the failure from cancelling the entire scope, we must handle the exception within the child coroutine.</p><h3>4. supervisorScope:</h3><p>Unlike a SupervisorJob, which only supervises its direct children in a CoroutineScope, supervisorScope {} is a special coroutine builder that ensures <strong>full failure isolation</strong> for all coroutines within the scope. It works like a SupervisorJob, but the entire scope becomes the supervisor.</p><p>The key distinction between supervisorScope and a CoroutineScope with SupervisorJob is that <strong>within a </strong><strong>supervisorScope, failures are isolated without the need for additional exception handling at the coroutine level</strong>. Any child coroutine’s failure does not propagate to its siblings or the parent scope.</p><h4>Key Characteristics of supervisorScope:</h4><ul><li>All coroutines launched inside a supervisorScope are automatically isolated from each other.</li><li>When a child coroutine fails, it is cancelled without affecting other coroutines in the scope.</li><li>No need for manual exception handling to prevent failure propagation.</li></ul><p>In this case, even though getData2() throws an exception, getData1() and getData3() are still printed because <strong>supervisorScope isolates failures by design</strong>.</p><h3>5. When to Use What:</h3><ul><li><strong>Use </strong><strong>coroutineScope</strong> when you need <strong>strict failure handling</strong>. If one coroutine fails, the entire group should fail to avoid inconsistency.</li><li><strong>Use </strong><strong>supervisorScope</strong> when you need <strong>resilience in the face of partial failure</strong>. Each coroutine can operate independently, and failure in one doesn&#39;t affect others.</li><li><strong>Use </strong><strong>CoroutineScope(SupervisorJob())</strong> when you want to supervise child coroutines but still need <strong>explicit exception handling</strong> for nested coroutines.</li></ul><p>In summary:</p><ul><li><strong>coroutineScope</strong> enforces strict failure handling across all child coroutines.</li><li><strong>supervisorScope</strong> isolates failures, allowing child coroutines to fail independently.</li><li><strong>Job</strong> propagates failure throughout the entire coroutine hierarchy.</li><li><strong>SupervisorJob</strong> supervises its direct children but requires manual exception handling for deeper failure isolation.</li></ul><p>Choosing the right tool depends on your concurrency requirements, but with a solid understanding of these concepts, you’ll be able to harness the full power of Kotlin’s coroutines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd0b80f8c6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Started Services in Android: Empowering Background Tasks with Control and Visibility!!]]></title>
            <link>https://medium.com/@adityamishra2217/understanding-started-services-in-android-empowering-background-tasks-with-control-and-visibility-bf161b855139?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf161b855139</guid>
            <category><![CDATA[services]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 09:06:17 GMT</pubDate>
            <atom:updated>2023-06-23T04:39:23.769Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0DCaaxbgqbRQpowJtCKs6A.jpeg" /></figure><blockquote>In the world of Android development, there are times when you need to perform tasks that should continue running even when your app is not in the foreground. Started services offer a powerful solution for executing long-running tasks in the background. In this blog, we will not only explore the concept of started services but also delve into foreground services — a specialized type of started service that provides enhanced control and visibility. We will examine real-life examples and explain why services are preferred over threads for background work.</blockquote><h3>What are Started Services:</h3><p>Started services in Android allow you to perform tasks in the background that continue executing independently of the application’s user interface. These services are explicitly started using the startService() method and stopped using stopService(). Unlike bound services that focus on inter-component communication, started services are ideal for tasks that require continuous execution and persist even when the app&#39;s user interface is not visible.</p><ol><li><strong><em>Long-running Tasks: </em></strong>Started services excel at executing long-running tasks such as music playback, file downloading, or location tracking. By leveraging a started service, you can ensure that these tasks continue seamlessly, even when the user switches to another app or locks the screen.</li><li><strong><em>Independent Lifecycle:</em></strong> Started services have their own lifecycle, decoupled from the app’s user interface. They persist even when the app is in the background or not visible, providing a reliable mechanism for executing background tasks.</li></ol><h3>Real-Life Examples:</h3><ol><li><strong><em>Music Player Application:</em></strong> Let’s consider a music player application. You want the music playback to continue uninterrupted, even if the user navigates away from the app or locks the screen. By implementing a started service — let’s call it MusicPlayerService—you can ensure that the music playback continues seamlessly in the background. The service&#39;s onStartCommand() method can handle the logic for starting and stopping music playback. With the appropriate configuration in the manifest file and service implementation, the music player service will continue running independently, enhancing the user experience.</li></ol><pre>class MusicPlayerService : Service() {<br><br>    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br>        // Logic to start playing music<br>        return START_STICKY // Service will be explicitly started and stopped<br>    }<br><br>    override fun onDestroy() {<br>        // Logic to stop playing music<br>        super.onDestroy()<br>    }<br><br>    override fun onBind(intent: Intent?): IBinder? {<br>// In case of started services we return binder as null<br>        return null<br>    }<br>}</pre><ol><li>In your activity or wherever you want to start the music playback, start the service using startService():</li></ol><p>To start the service in Kotlin:</p><pre>val serviceIntent = Intent(this, MusicPlayerService::class.java)<br>startService(serviceIntent)</pre><p>Make sure to add the service to the AndroidManifest.xml file:</p><pre>&lt;service<br>    android:name=&quot;.MusicPlayerService&quot;<br>    android:enabled=&quot;true&quot;<br>    android:exported=&quot;false&quot; /&gt;</pre><p>Here’s a more detailed explanation of each attribute:</p><ul><li>android:enabled:</li><li>When set to “true”, the service can be instantiated and used.</li><li>When set to “false”, the service cannot be instantiated or used.</li><li>Disabling a service is useful when you want to prevent its usage temporarily, such as during maintenance or specific conditions.</li><li>android:exported:</li><li>When set to “true”, the service can be accessed by components outside of your application.</li><li>When set to “false”, the service is private to your application and cannot be accessed by components from other applications.</li><li>Exporting a service makes it available for use by other applications or components, while not exporting it ensures that it can only be used within your application.</li></ul><p>In this example, the MusicPlayerService is enabled and can be accessed by other components or applications since android:exported is set to &quot;true&quot;.</p><p>2.<strong><em> File Downloading Application:</em></strong> Suppose you’re building a file downloading the application. To ensure that file downloads continue even when the user switches to another app, you can leverage a started service such as DownloadService. This service handles the file downloading logic in its onStartCommand() method, allowing downloads to proceed uninterrupted even if the user navigates away from the app or locks the screen. With the help of proper service configurations, the download service provides a seamless background download experience.</p><pre>class DownloadService : Service() {<br><br>    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br>        val fileUrl = intent?.getStringExtra(&quot;fileUrl&quot;)<br><br>        // Logic to download the file from the given URL<br><br>        return START_STICKY // Service will be explicitly started and stopped<br>    }<br><br>    override fun onDestroy() {<br>        // Logic to handle download cancellation or completion<br>        super.onDestroy()<br>    }<br><br>    override fun onBind(intent: Intent?): IBinder? {<br>        return null<br>    }<br>}</pre><p>To start the service for file downloading in Kotlin:</p><pre>val serviceIntent = Intent(this, DownloadService::class.java)<br>serviceIntent.putExtra(&quot;fileUrl&quot;, &quot;https://example.com/file.zip&quot;)<br>startService(serviceIntent)</pre><h3>Foreground Services:</h3><p>Foreground services are a specialized type of service that provides enhanced control and visibility to the user. They are started using the startForegroundService() method and require a notification to be displayed to the user while the service is running.</p><p>Difference between Started and Foreground Services: Started services, including foreground services, is explicitly started and stopped using the appropriate methods. However, foreground services offer additional benefits:</p><ol><li><strong><em>Ongoing Notification: </em></strong>Foreground services display an ongoing notification in the notification bar, ensuring that the user is aware of the service’s presence. This notification can provide relevant information and even allow the user to interact with the ongoing task.</li><li><strong><em>Priority and System Considerations:</em></strong> Foreground services receive higher priority than normal started services, allowing them to continue running even when system resources are constrained. They are less likely to be affected by system-imposed limitations, such as background execution limits.</li></ol><p><strong><em>When to Use Foreground Services: </em></strong>Foreground services are particularly useful in scenarios where ongoing user awareness and interaction are necessary. Some examples include:</p><ul><li>Music player applications display the current song being played and provide controls in the notification area.</li><li>VoIP (Voice over Internet Protocol) applications that provide ongoing call status and control options.</li></ul><h4>Why Not Use Threads Instead?</h4><p>You might wonder, why not use threads instead of services for background work? While threads are a viable option for background tasks, there are important considerations to keep in mind:</p><ol><li>Thread Lifecycle: Threads are tied to the lifecycle of the component that created them. If the component, such as an activity, is destroyed or paused, the threads associated with it are also affected. Services, on the other hand, have an independent lifecycle and can continue executing even when the component that started them is no longer active.</li><li>System-Imposed Limitations: Android imposes limitations on background execution to ensure a smooth user experience and efficient use of system resources. Services, especially foreground services, are designed to overcome these limitations and continue running even when the app is in the background.</li></ol><h3>Conclusion:</h3><p>Started services, including foreground services, provide a powerful mechanism for executing background tasks in Android applications. They offer independent lifecycles, ensuring task continuity even when the app is not in the foreground. Foreground services enhance control and visibility through ongoing notifications, enabling ongoing user awareness and interaction. By leveraging services, developers can build robust applications that deliver uninterrupted experiences and handle long-running tasks with efficiency. So, the next time you need to perform background work in your Android app, remember the strength and versatility of started and foreground services. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf161b855139" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing the Power of Lambda with Receiver in Kotlin for Android Development!!]]></title>
            <link>https://blog.devgenius.io/harnessing-the-power-of-lambda-with-receiver-in-kotlin-for-android-development-8779e8fc5321?source=rss-f000b5f6cd4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8779e8fc5321</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Adityamishra]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 18:14:44 GMT</pubDate>
            <atom:updated>2023-06-20T14:24:43.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*nRjcltV2eInbIBhxWg9Khg.png" /></figure><blockquote>Lambda with receiver is a powerful concept in Kotlin that can greatly enhance your Android development experience. By leveraging lambda with receiver, you can write concise and expressive code, create fluent APIs, and simplify common tasks. In this blog post, we will dive into the world of lambda with receiver and explore its innovative applications in Android development. Get ready to supercharge your Kotlin code!</blockquote><ol><li><strong><em>Simplifying RecyclerView Adapters: </em></strong>RecyclerView adapters are a fundamental component in Android development. Let’s see how lambda with receiver can simplify the process of creating and configuring RecyclerView adapters.</li></ol><pre>class MyAdapter(private val items: List&lt;String&gt;, private val onItemClick: (String) -&gt; Unit) :<br>    RecyclerView.Adapter&lt;MyAdapter.ViewHolder&gt;() {<br><br>    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {<br>        fun bind(item: String) {<br>            itemView.setOnClickListener { onItemClick(item) }<br>            itemView.textView.text = item<br>        }<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {<br>        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)<br>        return ViewHolder(view)<br>    }<br><br>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>        holder.bind(items[position])<br>    }<br><br>    override fun getItemCount(): Int {<br>        return items.size<br>    }<br>}</pre><p>In the above example, we create a RecyclerView adapter called MyAdapter. By using lambda with receiver, we pass the onItemClick lambda as a parameter, which allows us to handle item clicks easily. Here&#39;s an example of creating the adapter:</p><pre>val adapter = MyAdapter(items) { item -&gt;<br>    // Handle item click<br>    showToast(&quot;Clicked: $item&quot;)<br>}</pre><p>The lambda with receiver in the MyAdapter constructor provides a clean and concise way to handle item clicks. It enhances the readability and maintainability of the code.</p><p>2. <strong>Simplifying Dialog Creation</strong>: Dialogs are commonly used in Android apps for various purposes. Let’s explore how lambda with receiver can simplify the creation and customization of dialogs.</p><pre>fun showDialog(context: Context, init: AlertDialog.Builder.() -&gt; Unit) {<br>    val builder = AlertDialog.Builder(context)<br>    builder.init()<br>    val dialog = builder.create()<br>    dialog.show()<br>}</pre><p>In the above example, we define a showDialog function that takes a lambda with receiver of type AlertDialog.Builder. This allows us to customize the dialog properties and behavior easily. Here&#39;s an example usage:</p><pre>showDialog(context) {<br>    setTitle(&quot;Important Message&quot;)<br>    setMessage(&quot;This is an important dialog.&quot;)<br>    setPositiveButton(&quot;OK&quot;) { dialog, _ -&gt;<br>        dialog.dismiss()<br>    }<br>    setNegativeButton(&quot;Cancel&quot;) { dialog, _ -&gt;<br>        dialog.dismiss()<br>    }<br>}</pre><p>Using the lambda with receiver, we can chain multiple functions on the AlertDialog.Builder instance, making dialog creation and customization a breeze. The code becomes more readable and maintainable.</p><p><strong>3. Simplifying Shared Preferences Operations: </strong>Shared Preferences provide a simple way to store key-value pairs in Android. Let’s explore how lambda with receiver can simplify working with Shared Preferences.</p><pre>inline fun SharedPreferences.edit(func: SharedPreferences.Editor.() -&gt; Unit) {<br>    val editor = edit()<br>    editor.func()<br>    editor.apply()<br>}</pre><p>In the above example, we define an extension function edit on SharedPreferences that takes a lambda with receiver of type SharedPreferences.Editor. This allows us to easily modify shared preferences within the lambda. Here&#39;s an example usage:</p><pre>val sharedPreferences = context.getSharedPreferences(&quot;my_prefs&quot;, Context.MODE_PRIVATE)<br>sharedPreferences.edit {<br>    putString(&quot;key&quot;, &quot;value&quot;)<br>    putInt(&quot;count&quot;, 5)<br>    commit()<br>}</pre><p>By utilizing the lambda with receiver, we can chain multiple modifications to the shared preferences, making the code more concise and readable.</p><blockquote>Lambda with receiver is a powerful feature in Kotlin that can significantly simplify Android development. In this blog post, we explored innovative applications of lambda with receiver in Android, including simplifying RecyclerView adapters, dialog creation, and shared preferences operations. By harnessing the power of lambda with receiver, you can write cleaner, more expressive code that is easier to maintain. Embrace this powerful concept and take your Kotlin-based Android apps to the next level!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8779e8fc5321" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/harnessing-the-power-of-lambda-with-receiver-in-kotlin-for-android-development-8779e8fc5321">Harnessing the Power of Lambda with Receiver in Kotlin for Android Development!!</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>