<?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 Batuhan Gundogdu on Medium]]></title>
        <description><![CDATA[Stories by Batuhan Gundogdu on Medium]]></description>
        <link>https://medium.com/@batuhangundogdu?source=rss-39004c7fdb32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_8xrjKTa5CbGvu4oQcvEfg.jpeg</url>
            <title>Stories by Batuhan Gundogdu on Medium</title>
            <link>https://medium.com/@batuhangundogdu?source=rss-39004c7fdb32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:25:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@batuhangundogdu/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[How to Update MongoDB Documents by ObjectId in n8n: The Complete Guide]]></title>
            <link>https://medium.com/@batuhangundogdu/how-to-update-mongodb-documents-by-objectid-in-n8n-the-complete-guide-815e439daba5?source=rss-39004c7fdb32------2</link>
            <guid isPermaLink="false">https://medium.com/p/815e439daba5</guid>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[n8n]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Batuhan Gundogdu]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 00:04:48 GMT</pubDate>
            <atom:updated>2026-01-09T00:04:48.292Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The Problem That Drove Me Crazy for Hours</strong></h3><p>If you’ve ever tried to update a MongoDB document by its `_id` field in n8n, you’ve probably encountered this frustrating situation: your workflow runs successfully, shows no errors, but… nothing gets updated in the database.</p><p>I spent hours debugging this issue, trying every possible combination of query formats, only to discover that n8n’s MongoDB node has a fundamental limitation when it comes to ObjectId handling. In this article, I’ll share the solution that finally worked and save you the headache.</p><h3><strong>What Doesn’t Work (And Why)</strong></h3><h4><strong>Attempt 1: The `update` Operation with `updateKey`</strong></h4><p>The most intuitive approach is using the built-in `update` operation:</p><pre>Operation: Update<br>Collection: myCollection<br>Update Key: _id</pre><p><strong>Why it fails:</strong> When MongoDB returns documents via the `find` operation, the `_id` comes back as a string (e.g., `”6949486fb0654a7cf0313a60&quot;`). However, in the database, `_id` is stored as an `ObjectId`. The n8n MongoDB node doesn’t automatically convert the string back to ObjectId when matching documents.</p><h4><strong>Attempt 2: Extended JSON Format (`$oid`)</strong></h4><p>MongoDB’s Extended JSON format should work:</p><pre>{ &quot;_id&quot;: { &quot;$oid&quot;: &quot;6949486fb0654a7cf0313a60&quot; } }</pre><p><strong>Why it fails: </strong>n8n’s MongoDB node doesn’t parse Extended JSON in queries. Instead, it tries to create an ObjectId from the literal object `{ “$oid”: “…” }`, which throws an error: `”Argument passed in does not match the accepted types”`.</p><h4><strong>Attempt 3: `$expr` with `$toObjectId` in Update Query</strong></h4><p>Based on community suggestions, I tried:</p><pre>{<br>  &quot;$expr&quot;: {<br>    &quot;$eq&quot;: [&quot;$_id&quot;, { &quot;$toObjectId&quot;: &quot;{{ $json[&#39;_id&#39;] }}&quot; }]<br>  }<br>}</pre><p><strong>Why it fails:</strong> While `$toObjectId` works in aggregation pipelines, the n8n MongoDB node’s update operations don’t properly evaluate this expression in the query context. The update runs but matches zero documents.</p><h4><strong>The Solution: Aggregate with $merge</strong></h4><p>The key insight is that `$toObjectId` <strong>**does work**</strong> inside MongoDB aggregation pipelines. By using the `aggregate` operation with a `$merge` stage, we can perform updates with full control over ObjectId conversion.</p><h4><strong>The Working Pipeline</strong></h4><pre>[<br>  {<br>    &quot;$match&quot;: {<br>      &quot;$expr&quot;: {<br>        &quot;$eq&quot;: [&quot;$_id&quot;, { &quot;$toObjectId&quot;: &quot;{{ $json[&#39;_id&#39;] }}&quot; }]<br>      }<br>    }<br>  },<br>  {<br>    &quot;$set&quot;: {<br>      &quot;labels&quot;: {<br>        &quot;$setUnion&quot;: [<br>          { &quot;$ifNull&quot;: [&quot;$labels&quot;, []] },<br>          [&quot;my-new-label&quot;]<br>        ]<br>      }<br>    }<br>  },<br>  {<br>    &quot;$merge&quot;: {<br>      &quot;into&quot;: &quot;myCollection&quot;,<br>      &quot;whenMatched&quot;: &quot;replace&quot;<br>    }<br>  }<br>]</pre><h4><strong>Breaking Down the Pipeline</strong></h4><p>1. <strong>`$match` with `$toObjectId`</strong>: Finds the document by converting the string ID to ObjectId at query time</p><p>2. <strong>`$set` with `$setUnion`</strong>: Adds a label to an array without duplicates (equivalent to `$addToSet` in update operations)</p><p>3. <strong>`$merge`</strong>: Writes the modified document back to the collection</p><h4><strong>Node Configuration</strong></h4><pre>Operation: Aggregate<br>Collection: myCollection<br>Query: [the pipeline above]</pre><h4><strong>Critical Gotcha: The Loop-Breaking Bug</strong></h4><p>Here’s something that will save you another hour of debugging: <strong>`$merge` is a terminal stage that returns zero documents</strong>.</p><p>This means if your MongoDB node is inside a loop (like Split In Batches), the workflow will stop after the first iteration because there’s no output to pass to the next node.</p><h4><strong>The Fix</strong></h4><p>Enable `Always Output Data` on your MongoDB node:</p><pre>{<br>  &quot;parameters&quot;: { ... },<br>  &quot;alwaysOutputData&quot;: true<br>}</pre><p>Or in the n8n UI: Click on the node → Settings → Toggle “Always Output Data”</p><p>This ensures the node passes data downstream even when the aggregation returns nothing, allowing your loop to continue.</p><h3><strong>Complete Working Example</strong></h3><p>Here’s a real-world example that checks documents for certain content and adds labels:</p><h4><strong>Code Node (Prepare Data)</strong></h4><pre>const item = $input.first().json;<br><br>return [{<br>  json: {<br>    _id: String(item._id),  // Ensure it&#39;s a string<br>    shouldAddLabel: true<br>  }<br>}];</pre><h4><strong>MongoDB Node (Add Label)</strong></h4><pre>{<br>  &quot;operation&quot;: &quot;aggregate&quot;,<br>  &quot;collection&quot;: &quot;questioncontents&quot;,<br>  &quot;query&quot;: &quot;=[\n  { \&quot;$match\&quot;: { \&quot;$expr\&quot;: { \&quot;$eq\&quot;: [\&quot;$_id\&quot;, { \&quot;$toObjectId\&quot;: \&quot;{{ $json[&#39;_id&#39;] }}\&quot; }] } } },\n  { \&quot;$set\&quot;: { \&quot;labels\&quot;: { \&quot;$setUnion\&quot;: [{ \&quot;$ifNull\&quot;: [\&quot;$labels\&quot;, []] }, [\&quot;processed\&quot;]] } } },\n  { \&quot;$merge\&quot;: { \&quot;into\&quot;: \&quot;questioncontents\&quot;, \&quot;whenMatched\&quot;: \&quot;replace\&quot; } }\n]&quot;,<br>  &quot;alwaysOutputData&quot;: true<br>}</pre><h3><strong>Alternative Operations Using This Pattern</strong></h3><h4><strong>Adding to an Array (like $addToSet)</strong></h4><pre>{<br>  &quot;$set&quot;: {<br>    &quot;tags&quot;: {<br>      &quot;$setUnion&quot;: [<br>        { &quot;$ifNull&quot;: [&quot;$tags&quot;, []] },<br>        [&quot;new-tag&quot;]<br>      ]<br>    }<br>  }<br>}</pre><h4><strong>Removing from an Array (like $pull)</strong></h4><pre>{<br>  &quot;$set&quot;: {<br>    &quot;tags&quot;: {<br>      &quot;$filter&quot;: {<br>        &quot;input&quot;: { &quot;$ifNull&quot;: [&quot;$tags&quot;, []] },<br>        &quot;cond&quot;: { &quot;$ne&quot;: [&quot;$$this&quot;, &quot;tag-to-remove&quot;] }<br>      }<br>    }<br>  }<br>}</pre><h4><strong>Updating a Field</strong></h4><pre>{<br>  &quot;$set&quot;: {<br>    &quot;status&quot;: &quot;completed&quot;,<br>    &quot;updatedAt&quot;: &quot;$$NOW&quot;<br>  }<br>}</pre><h4><strong>Incrementing a Counter</strong></h4><pre>{<br>  &quot;$set&quot;: {<br>    &quot;viewCount&quot;: { &quot;$add&quot;: [{ &quot;$ifNull&quot;: [&quot;$viewCount&quot;, 0] }, 1] }<br>  }<br>}</pre><h3><strong>Key Takeaways</strong></h3><p>1. <strong>Use `aggregate` operation</strong> instead of `update` when you need to match by ObjectId</p><p>2. <strong>`$toObjectId`</strong> only works inside aggregation pipeline stages</p><p>3. <strong>`$merge`</strong> writes changes back to the collection but returns zero documents</p><p>4. <strong>Enable `alwaysOutputData`</strong> to prevent loop-breaking when using `$merge`</p><p>5. <strong>`$setUnion`</strong> is your friend for adding to arrays without duplicates</p><p>This pattern has been rock-solid in production, processing thousands of documents without issues. I hope this saves you the hours of debugging I went through!</p><p><em>Have you encountered other n8n + MongoDB quirks? Drop a comment below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=815e439daba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build What Matters: The Wild, Wacky Dance of Problem and Solution Spaces]]></title>
            <link>https://medium.com/@batuhangundogdu/build-what-matters-the-wild-wacky-dance-of-problem-and-solution-spaces-25e8a914e276?source=rss-39004c7fdb32------2</link>
            <guid isPermaLink="false">https://medium.com/p/25e8a914e276</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Batuhan Gundogdu]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 06:36:17 GMT</pubDate>
            <atom:updated>2025-02-25T06:36:17.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A high-quality photo of a half-built house with a blueprint in the foreground." src="https://cdn-images-1.medium.com/max/1024/1*THjpnYSaqNynGTB4_Kr9sg.png" /><figcaption>Every great app starts with a plan.</figcaption></figure><p>Imagine a master builder, sweat dripping from his brow, standing triumphantly atop a construction site. He’s obsessed over every nail, every beam, every gleaming screw — premium stuff, top-notch craftsmanship. The foundation? A work of art. The only hitch? He forgot to ask the homeowner what they wanted. While he’s marveling at his architectural masterpiece, they’re scratching their head, muttering, “I just needed a cozy cabin, not a fortress with a moat.” Cue the facepalm.</p><p>This, my friends, is the app development trap we tumble into more often than we’d care to admit. We get lost in the shiny gears of code and forget the big picture. Enter two heavyweight concepts: <strong>Product vs Software</strong> and <strong>Problem Space vs Solution Space</strong>. They’re the secret sauce to building something people actually want — and not just a tech demo for your GitHub portfolio. What if I told you that building an app is a lot like building a house — and your code is just the screws?</p><h3>Product vs Software: Screws Don’t Make a Home</h3><p>Let’s kick things off with a tasty analogy. Picture yourself whipping up dinner. The <strong>software</strong> is your recipe — the precise steps, the fancy knife techniques, the sizzling alchemy of ingredients. It’s the grunt work that makes the magic happen. But the <strong>product</strong>? That’s the steaming plate of perfection you set on the table — the flavors that make your taste buds dance, the satisfaction that fills your belly. Nobody’s raving about your mise en place skills; they’re raving because the meal hit the spot.</p><p>In app land, <strong>software</strong> is the engine room: the Swift code, the Python scripts, the cloud voodoo that keeps the wheels spinning. It’s the nuts and bolts, the 1s and 0s, the stuff that makes nerds like me giddy. But the <strong>product</strong> is what the user hugs — it’s the seamless onboarding, the “oh, that’s handy” feature, the moment they think, “This app gets me.”</p><figure><img alt="A simple side-by-side comparison chart." src="https://cdn-images-1.medium.com/max/902/1*QPJtP4GhE9coGhex_bi15A.png" /></figure><p>Here’s the kicker: obsess over the software alone, and you’re that builder polishing screws while the homeowner’s still dreaming of a porch swing. I once watched a team spend weeks perfecting an algorithm’s efficiency — only to realize users didn’t care about speed; they wanted clarity. The product is the promise you make; the software is how you deliver. Mix them up, and you’re serving raw dough instead of a baked masterpiece.</p><h3>Problem Space: Playing Detective in User Land</h3><figure><img alt="An image of a detective board with sticky notes, red string, and clues, or a photo of someone conducting a user interview." src="https://cdn-images-1.medium.com/max/1024/1*o0yeZTKn0O1IJJfGIPvyTw.png" /><figcaption>Uncovering the real problem, one clue at a time.</figcaption></figure><p>Now, let’s swap hats. You’re Sherlock Holmes, pipe optional, sniffing out clues in the foggy streets of the <strong>problem space</strong>. This is where you dig into the messy, human heart of it all: What’s bugging your users? What’s their daily grind like? What’s the itch they can’t scratch?</p><p>Say you’re building a budgeting app. The surface-level problem might be “tracking expenses.” Easy, right? Slap some charts on it and call it a day. But hold your magnifying glass closer. Maybe it’s not about numbers — it’s about quelling the anxiety of an overdrawn account, or dodging that cringe-worthy “we need to talk money” chat with their spouse. The problem space isn’t just “what”; it’s “why.”</p><p>Getting this right means channeling your inner spy. Shadow users as they fumble through their day. Fire off questions like, “What sucks about this? What’s your dream fix?” Run surveys that don’t bore them to death. I once sat with a user who confessed they’d rather guess their balance than wrestle with a clunky spreadsheet. That’s gold — pure, unfiltered problem-space gold. Skip this step, and you’re Sherlock arresting the wrong suspect because their mustache looked suspicious. Empathy isn’t fluffy; it’s your superpower.</p><h3>Solution Space: Where the Geek Magic Happens</h3><p>Got the problem pinned? Awesome. Now strut into the <strong>solution space</strong>, your personal workshop of wonders. This is where you roll up your sleeves and get technical — choosing frameworks, sketching architectures, writing code that hums. It’s the “how” to the problem’s “what.”</p><figure><img alt="A photo of a craftsman’s toolbox or a close-up of hands working on a technical project (e.g., coding on a laptop or assembling parts)." src="https://cdn-images-1.medium.com/max/1024/1*-kjHZpnvPBhePkUc3ySf0w.png" /><figcaption>Crafting solutions, one tool at a time.</figcaption></figure><p>Let’s stick with that budgeting app. Maybe you opt for a lightweight SQLite database for snappy local storage, or sprinkle in some SwiftUI for a slick, animated UI that feels like butter. You’re balancing trade-offs: Do you prioritize speed or scalability? Native or cross-platform? It’s like picking the right spice for your stew — too much, and it’s overpowering; too little, and it’s bland.</p><p>Here’s where the “under the hood” fun kicks in. You might wrestle with memory management to keep the app lean — think ARC (Automatic Reference Counting) in Swift to dodge those pesky leaks. Or maybe you’re tweaking API calls to shave milliseconds off load times, because nobody likes a spinner that overstays its welcome. But — and this is huge — none of this matters if it doesn’t serve the problem. Ever built a feature so over-the-top it’s like strapping jet engines to a skateboard? Guilty. The trick is keeping your geek glee tethered to the user’s needs.</p><h3>The Dance: A Two-Step That Wins Hearts</h3><p>Building something great isn’t a straight line — it’s a dance, a sizzling tango between problem and solution. You dip into the problem space to hear the user’s woes, twirl into the solution space to craft a fix, then sashay back to see if it lands. It’s a conversation, not a monologue.</p><p>Picture this: You’re cooking up a travel app. Users grumble about “trip planning being a hassle.” You whip up a quick itinerary builder (solution), test it, and — plot twist — they’re overwhelmed by choices, not time. Back to the problem space you go, uncovering their real beef: decision fatigue. So, you pivot to a smart recommendation engine. Each step refines both what you know and what you build.</p><figure><img alt="A circular flowchart or looping arrow diagram showing the iterative process between “Problem Space” and “Solution Space.”" src="https://cdn-images-1.medium.com/max/668/1*DgjVAlaajSBkt3VlFKJ0Bw.png" /><figcaption>The development dance: a loop of learning and building.</figcaption></figure><p>This rhythm — listen, prototype, tweak — is why agile teams live for sprints. It’s not a stiff march; it’s a groove. Ever heard the phrase “fail fast”? That’s this dance in action. You’re not failing — you’re finding the beat.</p><h3>Pitfalls: Where We Faceplant (and Laugh About It)</h3><p>We’ve all tripped over our own brilliance. Here are two classics:</p><ol><li><strong>The Code-First Crusader:</strong> This dev hears “make it better” and bolts to their IDE, churning out lines like a caffeinated poet. I once optimized a dashboard’s load time to microseconds — only to learn “better” meant “easier to read.” The user didn’t care about my Big O flex; they wanted bigger fonts. Ouch.</li><li><strong>The Solution Soulmate:</strong> You fall hard for your first idea. I did this in 2019, clinging to a feature like it was my firstborn, even as testers yawned. Feedback begged for change, but I was too smitten. Spoiler: It flopped. Lesson: Don’t marry your code — date it.</li></ol><p>How do you dodge these? Pause. Validate the problem before you type func. Stay loose — your first stab rarely nails it. As some wise tech sage probably said, “Love the problem, not the solution.” Preach.</p><h3>Under the Hood: Tech Tricks to Keep It Smooth</h3><p>Time to lift the hood and get greasy — without losing you in the weeds. The solution space thrives on smart choices, so here’s a peek at what keeps the engine purring:</p><ul><li><strong>Tool Time:</strong> Match your stack to the mission. Building a quick MVP? Firebase might be your buddy. Eyeing a million users? Plan for distributed systems — think microservices or a beefy PostgreSQL setup. It’s like packing for a hike: boots for the trail, not flip-flops.</li><li><strong>Test Like You Mean It:</strong> Unit tests catch bugs before they bite; user tests catch “nobody wants this” moments. Ever used XCTest to mock an API? It’s like a stunt double for your app — safe and revealing. A/B testing’s your bonus round: Does feature X beat Y? Data doesn’t lie.</li><li><strong>Keep It Lean:</strong> Over-engineering is a trap. If a switch statement solves it, don’t architect a factory pattern. I once bloated an app with unnecessary abstractions — users felt the lag, not my cleverness. Less is more.</li><li><strong>Automate the Grunt Work:</strong> CI/CD pipelines (hello, GitHub Actions) deploy faster than you can say “merge.” Linting keeps your code clean; automated tests save your sanity. It’s like hiring a robot butler to handle the dishes while you sip coffee.</li></ul><p>These aren’t just nerd flexes — they’re guardrails. They free you to obsess over the problem, not the plumbing.</p><h3>Tips to Rock This Gig</h3><p>Ready to ace this? Here’s your playbook:</p><ul><li><strong>Eavesdrop Like a Pro:</strong> User interviews are your intel. Ask, “What’s the worst part of this?” then zip it. Silence unearths gems.</li><li><strong>Prototype Like a Maniac:</strong> Sketch rough drafts — think paper mocks or Figma clicks. Test them fast. A bad idea’s cheaper to trash at this stage.</li><li><strong>Remix Like a DJ:</strong> Feedback’s your beat. Tweak, test, repeat. Each spin gets you closer to a banger.</li><li><strong>Stay Chill:</strong> Your first solution’s a rough draft. Pivot when it flops — it’s growth, not defeat.</li><li><strong>Chase the Vibe:</strong> Users don’t geek out on your closures; they vibe on how your app feels. Aim for “wow,” not just “works.”</li></ul><h3>Wrap-Up: Build a Home, Not a Tech Shrine</h3><p>Here’s the gospel: killer apps aren’t about pristine code — they’re about nailing problems with solutions that fit like a glove. <strong>Product</strong> beats software when you zoom out to the user’s world. The <strong>problem space</strong> is your north star; the <strong>solution space</strong> is your rocket fuel. Dance between them, and you’ll craft something that doesn’t just run — it sings.</p><p>Next time you’re itching to code, stop. Ask: <em>What’s this house for, and who’s calling it home?</em> Then build something worth living in.</p><figure><img alt="A photo of a finished, cozy house with a family moving in." src="https://cdn-images-1.medium.com/max/1024/1*TXIDMzA-yaa4uP7fRUC3kA.png" /><figcaption>A home — or app — built to last.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25e8a914e276" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Sneaky Power of Combine’s Just for One-Shot HTTP Requests]]></title>
            <link>https://medium.com/@batuhangundogdu/the-sneaky-power-of-combines-just-for-one-shot-http-requests-f11e3893a9a5?source=rss-39004c7fdb32------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11e3893a9a5</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[just]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Batuhan Gundogdu]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 14:48:01 GMT</pubDate>
            <atom:updated>2025-02-11T14:48:01.145Z</atom:updated>
            <content:encoded><![CDATA[<p>The lesser-known hero that might just save your day</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IcJ19n9DxbIdG8Pg" /><figcaption>Photo by <a href="https://unsplash.com/@marcojodoin?utm_source=medium&amp;utm_medium=referral">Marc-Olivier Jodoin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Combine is full of shiny Publishers — dataTaskPublisher, Future, you name it. But have you ever taken a closer look at Combine’s <strong>Just</strong> publisher? If your brain just went, “Pshh… that little thing that emits one value and calls it a day?” — buckle up. We’re about to uncover why Just can be your new best friend for those quick, single-response network tasks.</p><h4><strong>The “Single and Done” Mindset</strong></h4><p>Picture this: You have a small piece of data you need from a server — maybe it’s a one-off analytics event or a short user preference check. You don’t need a big pipeline with all the error-handling bells and whistles. You just want to do the request, get a single piece of data (or a fallback), and wrap it up. That’s precisely where Just shines.</p><pre>// The &#39;fire once and forget&#39; approach<br>Just(&quot;Hello, Combine!&quot;)<br>    .sink { value in<br>        print(&quot;Received value: \(value)&quot;) // &quot;Received value: Hello, Combine!&quot;<br>    }</pre><p>It’s that simple. One emission, no nonsense.</p><p>But if you’re thinking, “Wait, what about network errors? Doesn’t Just have a Failure type of Never?” — you’re absolutely right. That can bite you if you’re not prepared. Which leads us to…</p><h4><strong>The Quick-and-Easy POST Extension</strong></h4><p><em>“But how am I supposed to use a ‘Never’-failing publisher for network calls?”</em> Don’t worry; we have a neat trick. We’ll just (pun intended) catch errors upstream and turn them into a fallback. Boom — problem solved! Here’s a ready-to-copy extension you can plop right into your project for a quick POST request:</p><pre>import Combine<br>import Foundation<br><br>extension Just where Output == Data {<br>    <br>    /// Makes a single-shot HTTP POST request to the specified URL,<br>    /// emitting a single Data value (or an empty Data on error).<br>    ///<br>    /// - Parameters:<br>    ///   - url: The URL to POST to.<br>    ///   - body: The HTTP body to send (optional).<br>    ///   - headers: Any additional HTTP headers.<br>    /// - Returns: An AnyPublisher&lt;Data, Never&gt; that emits one Data value and completes.<br>    static func post(to url: URL,<br>                     body: Data? = nil,<br>                     headers: [String: String] = [:]) -&gt; AnyPublisher&lt;Data, Never&gt; {<br>        var request = URLRequest(url: url)<br>        request.httpMethod = &quot;POST&quot;<br>        request.httpBody = body<br>        headers.forEach { field, value in<br>            request.setValue(value, forHTTPHeaderField: field)<br>        }<br>        <br>        return URLSession.shared.dataTaskPublisher(for: request)<br>            .map(\.data)<br>            // If an error occurs, switch to a Just with empty Data.<br>            .catch { _ in Just(Data()) }<br>            .eraseToAnyPublisher()<br>    }<br>}</pre><p><strong>Why This Works</strong></p><ul><li><strong>One Emission</strong>: URLSession does the heavy lifting, but at the end, we funnel that single chunk of data into Just.</li><li><strong>No-Fail Guarantee</strong>: If something <em>does</em> go wrong, we catch the error and publish an empty Data as a fallback. Your pipeline stays alive, never failing downstream.</li><li><strong>Copy &amp; Paste Friendly</strong>: Throw this extension in your project, and you’re good to go.</li></ul><p>Using it is a breeze:</p><pre>import Combine<br><br>var cancellables = Set&lt;AnyCancellable&gt;()<br><br>Just.post(to: URL(string: &quot;https://api.example.com/newitem&quot;)!,<br>          body: &quot;{ \&quot;title\&quot;: \&quot;Hello\&quot; }&quot;.data(using: .utf8),<br>          headers: [&quot;Content-Type&quot;: &quot;application/json&quot;])<br>    .sink { data in<br>        // Data or fallback is yours to handle<br>        print(&quot;POST response size: \(data.count) bytes&quot;)<br>    }<br>    .store(in: &amp;cancellables)</pre><h4><strong>But, But… What About Errors?</strong></h4><p>Yes, Just is basically wearing error-canceling headphones. It doesn’t want to hear about your “network not reachable” or your “401 Unauthorized.” It just wants to emit its one piece of data and exit stage left.</p><p>If that’s not your jam — if you’re the type who needs to know <em>exactly</em> why a request failed — then Just might not cut it. You’ll want a Future or keep using dataTaskPublisher as-is, so you can throw all the error debugging you crave. But if your app can live with a fallback or a no-op on failure, Just is your friend.</p><h4><strong>Concurrency, Anyone?</strong></h4><p>You’re not limited to single usage. Do you have multiple endpoints to hit simultaneously? Fire up multiple Just.post(…)calls and combine them:</p><pre>let publisherA = Just.post(to: someURL)<br>let publisherB = Just.post(to: anotherURL)<br><br>publisherA<br>    .zip(publisherB)<br>    .sink { dataA, dataB in<br>        // Combined data from both<br>        print(&quot;Data A size: \(dataA.count), Data B size: \(dataB.count)&quot;)<br>    }<br>    .store(in: &amp;cancellables)</pre><p>All those requests happen in parallel, each returning a single emission. Perfect for small tasks that either get done fast or fallback quickly.</p><h4><strong>When (and When Not) to Lean on Just</strong></h4><p>Now, don’t go replacing <em>all</em> your network calls with Just.post(…). Like singletons, Just is a pattern you want to use wisely:</p><p><strong>Use Just</strong> When:</p><ul><li>You only need a single piece of data (and you’re cool with ignoring detailed errors).</li><li>You want quick, test-friendly code, possibly returning a known fallback.</li><li>You’re orchestrating multiple small tasks in parallel and don’t want them to fail your entire pipeline.</li></ul><p><strong>Avoid Just</strong> When:</p><ul><li>Error handling is crucial (e.g., you must show an alert for a 403 Forbidden).</li><li>You’re streaming data continuously (then you want a different type, like PassthroughSubject or dataTaskPublisher directly).</li><li>The request might produce multiple emissions over time (like a WebSocket or chunked downloads).</li></ul><h4><strong>Building a Clean, Lean Architecture</strong></h4><p>One-shot or not, keep your code tidy:</p><ol><li><strong>Network Layer</strong>: Put the extension (or other network code) in a dedicated place.</li><li><strong>ViewModel/Business Logic</strong>: Subscribes to the publisher, transforms data as needed, and updates app state.</li><li><strong>UI</strong>: Observes published changes and re-renders.</li></ol><p>Let Just remain a small puzzle piece in a larger, well-organized system.</p><h4>The Bottom Line</h4><p>Sometimes you just want a <em>tiny</em> one-shot network call that either works or quietly fails. That’s where Just strolls in with a casual “Sure thing, boss!” and does the job. Quick, simple, no fuss.</p><ul><li>It’s not a universal replacement for robust error handling.</li><li>It plays nicely with Combine operators for chaining or parallel requests.</li><li>It keeps code short and sweet for those no-brainer tasks that don’t need rocket science.</li></ul><p>So the next time you’re about to spin up a complicated pipeline for a small, single-response request, pause. Ask yourself: <em>Is this a job for Just?</em> If so, you’ve got the extension and the know-how to pull it off. Embrace the single-emission simplicity — and watch your code stay wonderfully easy to read (and maintain).</p><p><strong>Happy coding!</strong> And remember, small tasks deserve small solutions. Just might be all you need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11e3893a9a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom Combine Publishers with Swift’s Structured Concurrency]]></title>
            <link>https://medium.com/@batuhangundogdu/building-custom-combine-publishers-with-swifts-structured-concurrency-15c136193b3a?source=rss-39004c7fdb32------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c136193b3a</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Batuhan Gundogdu]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 10:54:21 GMT</pubDate>
            <atom:updated>2025-02-10T10:54:21.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nWO3oQzxWhBUCPTj" /><figcaption>Photo by <a href="https://unsplash.com/@thomaschan523?utm_source=medium&amp;utm_medium=referral">Thomas Chan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Combine</em> is Apple’s native reactive framework, allowing you to process values over time, handle asynchronous work elegantly, and chain operations in a declarative manner. Despite a host of built-in publishers and operators (like URLSession.DataTaskPublisher, Just, or PassthroughSubject), there are times when crafting a <em>custom publisher</em> can give you finer control, especially around concurrency, backpressure, and error management.</p><p>In this article, we’ll walk through how to write a custom Combine publisher and subscriber from the ground up. We’ll use <strong>image downloading</strong> as our central example — demonstrating concurrency with Swift’s structured concurrency, handling parallel downloads, and managing backpressure effectively. By the end, you’ll be equipped with practical insights for building robust, high-performance reactive components in iOS apps.</p><h4><strong>Table of Contents</strong></h4><ol><li>How the Publisher-Subscriber Model Works in Combine</li><li>Why Create a Custom Publisher?</li><li>Introducing ImageDownloadPublisher and ImageDownloadSubscriber</li><li>Concurrency with Swift’s Structured Concurrency</li><li>Backpressure Management</li><li>Concurrency Safeguards and Best Practices</li><li>Error Handling and Extensibility</li><li>Performance Optimizations and Clean Architecture</li><li>Summary and Key Takeaways</li></ol><h3><strong>How the Publisher-Subscriber Model Works in Combine</strong></h3><p>At the heart of Combine is the <strong>Publisher–Subscriber</strong> pattern:</p><ul><li>A <strong>Publisher</strong> emits values (or a completion event) over time.</li><li>A <strong>Subscriber</strong> receives those values and can process them.</li><li>A <strong>Subscription</strong> is the connection between the publisher and subscriber. It’s responsible for forwarding demand requests (backpressure) and values from publisher to subscriber.</li></ul><p>Key points to remember:</p><ol><li><strong>A publisher can have multiple subscribers</strong>, but each subscriber has a single subscription to that publisher.</li><li>When a subscriber subscribes, the publisher creates a Subscription object and hands it over to the subscriber.</li><li>The subscriber can request values (demand) from the publisher. Combine’s backpressure model ensures that publishers don’t overwhelm subscribers with more data than they can handle.</li></ol><h3><strong>Why Create a Custom Publisher?</strong></h3><p>Combine provides many out-of-the-box publishers (Just, PassthroughSubject, CurrentValueSubject, and various operators like map, flatMap, etc.). Often, these are enough to handle everyday asynchronous tasks. So, <strong>why roll your own?</strong></p><ol><li><strong>Fine-grained Control Over Concurrency</strong>: Sometimes you need to run tasks in parallel, perform specific cancellation logic, or manage resources carefully.</li><li><strong>Handling Custom Backpressure</strong>: If you want to throttle or batch emissions, you can implement your own request(_:)method in your subscription.</li><li><strong>Custom Logic or Integrations</strong>: You might integrate with a proprietary SDK or a hardware device that doesn’t have Combine support. Writing a publisher ensures your custom logic plays well with the rest of your reactive pipeline.</li></ol><h3><strong>Introducing ImageDownloadPublisher and ImageDownloadSubscriber</strong></h3><p>Below is a simplified example of a custom publisher and subscriber. It downloads a list of images in parallel, storing each in the app’s documents directory, then emits the file URL back to the subscriber.</p><pre>struct ImageDownloadPublisher: Publisher {<br>    typealias Output = URL<br>    typealias Failure = Never<br><br>    let urls: [URL]<br><br>    func receive&lt;S&gt;(subscriber: S) <br>    where S: Subscriber, Never == S.Failure, URL == S.Input {<br>        let subscription = ImageDownloadSubscription(urls: urls, subscriber: subscriber)<br>        subscriber.receive(subscription: subscription)<br>    }<br>}</pre><p>The ImageDownloadPublisher defines:</p><ul><li><strong>Output = URL</strong>: It emits URL values once images are downloaded.</li><li><strong>Failure = Never</strong>: For simplicity, we aren’t handling errors in this basic version (though you <em>can</em> define a custom Failureto propagate download errors).</li><li><strong>receive(subscriber:)</strong>: Creates a Subscription that ties our custom logic to the subscriber.</li></ul><h4><strong>The Custom Subscriber</strong></h4><p>A subscriber receives values and can handle backpressure. Here, ImageDownloadSubscriber is designed to:</p><ol><li>Use Swift’s concurrency (Task + withTaskGroup) to download images in parallel.</li><li>Emit each downloaded file URL to the attached subscriber.</li><li>Signal completion when all downloads finish.</li></ol><pre>class ImageDownloadSubscriber&lt;S: Subscriber&gt;: Subscriber <br>where S.Input == URL?, S.Failure == Never {<br>    let urls: [URL]<br>    var subscriber: S?<br><br>    init(urls: [URL], subscriber: S) {<br>        self.urls = urls<br>        self.subscriber = subscriber<br><br>        Task {<br>            await startDownload()<br>        }<br>    }<br><br>    private func startDownload() async {<br>        await withTaskGroup(of: URL?.self) { group in<br>            for url in urls {<br>                group.addTask {<br>                    let response = try? await URLSession.shared.data(from: url)<br>                    if let data = response?.0 {<br>                        let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!<br>                        let fileURL = docDir.appendingPathComponent(url.lastPathComponent)<br>                        try? data.write(to: fileURL)<br>                        return fileURL<br>                    }<br>                    return nil<br>                }<br>            }<br><br>            // As each task completes, emit a value to the subscriber<br>            for await url in group {<br>                subscriber?.receive(url)<br>            }<br>            subscriber?.receive(completion: .finished)<br>        }<br>    }<br><br>    func request(_ demand: Subscribers.Demand) {<br>        // Handle backpressure if needed<br>    }<br><br>    func cancel() {<br>        subscriber = nil<br>    }<br>}</pre><h3><strong>Concurrency with Swift’s Structured Concurrency</strong></h3><p>ImageDownloadSubscriber is a good illustration of how Combine can interoperate with Swift’s concurrency features.</p><ul><li><strong>Task { await startDownload() }</strong>: Spins off a new task to run downloads asynchronously.</li><li><strong>withTaskGroup(of: URL?.self)</strong>: Creates a task group to run multiple downloads in parallel. Each addTask block executes concurrently, and you can await results in a for-await loop.</li><li><strong>Thread Safety</strong>: Swift tasks run on appropriate threads in the background. You typically don’t need to worry about manual thread management, but you <em>do</em> need to consider shared data and synchronization (for instance, updating shared state from multiple tasks).</li></ul><p><strong>Why structured concurrency?</strong> It ensures tasks are canceled automatically if the parent is canceled, it provides clear scoping, and prevents typical pitfalls with concurrency (like forgetting to release a thread or leaving tasks orphaned). This design also meshes well with Combine’s model: once your subscriber is canceled, you can cancel these tasks or just stop emitting values.</p><h3><strong>Backpressure Management</strong></h3><p>Backpressure is <em>Combine’s</em> way of saying: “Don’t send me more items than I can handle.” A subscriber declares how many values it’s prepared to receive at a time via request(_:).</p><p>In the snippet above:</p><pre>func request(_ demand: Subscribers.Demand) {<br>    // Handle backpressure if needed<br>}</pre><p>Right now, we ignore backpressure because we always try to emit downloaded URLs as soon as they’re ready. But in a more advanced scenario — say you’re streaming a massive data feed or performing CPU-intensive operations — you could:</p><ol><li>Keep track of how many items you’re allowed to emit (.max(10), for example).</li><li>Pause or buffer tasks if you’ve exceeded the demand.</li><li>Resume sending values when the subscriber requests more.</li></ol><p>This <em>manual control</em> is one of the primary reasons for writing custom publishers: you decide how to handle or throttle the flow of data.</p><h3><strong>Concurrency Safeguards and Best Practices</strong></h3><p>When running concurrent tasks, you need to consider <strong>thread safety</strong>. The snippet above downloads images in parallel, then uses subscriber?.receive(url).</p><p><strong>Potential pitfalls</strong>:</p><ol><li><strong>Race Conditions</strong>: If multiple tasks modify shared state (like subscriber or a global resource), you could have inconsistent behavior.</li><li><strong>Cancellation Handling</strong>: If the subscriber cancels the subscription (by calling .cancel()), you might want to cancel the tasks.</li></ol><h4><strong>Using Actors or Dedicated Queues</strong></h4><ul><li><strong>Actors</strong> in Swift 5.5+ provide a simple way to ensure mutable state is accessed safely. For instance, you could store a reference to the subscriber inside an actor that enforces serial access.</li><li><strong>Serial Dispatch Queues</strong>: For older Swift code or more manual control, you can dispatch your subscription logic onto a serial queue, ensuring no race conditions.</li></ul><h4><strong>Stopping or Canceling Tasks</strong></h4><p>When the subscriber calls .cancel(), we set subscriber = nil. In a production-level approach, you might also want to keep track of all child tasks in the subscription and immediately cancel them. This can be done by storing references to tasks returned by group.addTask.</p><h3><strong>Error Handling and Extensibility</strong></h3><p>Our example uses Failure = Never to simplify things, but real-world downloads can fail. If you need to propagate errors:</p><ol><li><strong>Define a custom Error:</strong></li></ol><p>2. <strong>Change</strong> typealias Failure = DownloadError <strong>in your publisher</strong>:</p><pre>struct ImageDownloadPublisher: Publisher {<br>    typealias Output = URL<br>    typealias Failure = DownloadError<br>    ...<br>}</pre><p>3. <strong>Emit errors</strong>:</p><ul><li>Instead of subscriber?.receive(nil), you might call subscriber?.receive(completion: .failure(.networkError)).</li><li>The subscriber can then handle that failure gracefully.</li></ul><p>By embracing a custom error type, your publisher can communicate more nuanced failure states — perhaps some URLs failed, while others succeeded. You can design a resilient subscriber that logs errors, retries, or presents user-facing alerts.</p><h3><strong>Performance Optimizations and Clean Architecture</strong></h3><p>When downloading large sets of images or performing CPU-intensive work:</p><ol><li><strong>Tune withTaskGroup concurrency</strong>: Control the number of tasks in flight if resources are limited. Swift’s concurrency is generally well-optimized, but you can batch or limit concurrency using your own logic (e.g., only add tasks if group.currentTaskCount &lt; maxParallelDownloads).</li><li><strong>Batch Emissions</strong>: Instead of emitting each URL as soon as it’s ready, you could collect them and emit them as a batch. This approach can reduce overhead if a subscriber is doing heavy processing for each item.</li><li><strong>Separate Publisher Logic from Networking</strong>: Keep your custom publisher small and focused on bridging Combine with concurrency. Place any heavy business logic in dedicated classes or structs. This makes your code easier to test and maintain.</li></ol><h4><strong>Clean Architecture Guidelines</strong></h4><ul><li><strong>Publisher</strong>: Should handle <strong>subscription creation</strong>, define <strong>Output</strong> and <strong>Failure</strong>, and orchestrate emission of values.</li><li><strong>Subscriber</strong>: Should know <strong>how to handle</strong> the completion and values, plus manage demand.</li><li><strong>Networking or Business Layer</strong>: Separate your actual network logic. For instance, you might have a ImageDownloadManager or ImageService that knows how to fetch and save files.</li><li><strong>UI and App Layer</strong>: Subscribes to your publisher, updates the UI, handles user interactions.</li></ul><p>Keeping these concerns distinct means you can evolve and reuse each layer independently.</p><h3><strong>Summary and Key Takeaways</strong></h3><p><strong>Custom Combine publishers</strong> offer powerful flexibility for iOS developers who want more control over their asynchronous pipelines. By leveraging <strong>Swift’s structured concurrency</strong>, you can run tasks in parallel, handle cancellations gracefully, and keep your code expressive and safe. <strong>Backpressure</strong> is a crucial concept, ensuring that a subscriber isn’t flooded with more data than it can process, and custom publishers give you the reins to implement it precisely. Finally, by carefully <strong>separating concerns</strong> (networking, concurrency, and business logic) and incorporating best practices for <strong>thread safety</strong> (actors, dispatch queues, or cancellation strategies), you’ll avoid common pitfalls and create reactive components that scale elegantly.</p><p>Whether you’re building a complex data processing pipeline or integrating with hardware, learning to write your own publisher unlocks the full potential of Combine. Keep an eye on concurrency nuances, be mindful of error reporting, and structure your code so that each layer has a well-defined responsibility. You’ll end up with a robust, maintainable solution that takes full advantage of Swift’s modern concurrency and reactive programming paradigms.</p><p><strong>Thanks for reading!</strong> With these insights, you should feel confident in shaping your custom publishers for real-world use. Swift’s concurrency features combined with Combine’s backpressure model provide an elegant foundation for advanced asynchronous programming. Give custom publishers a try in your next project, and enjoy the benefits of cleaner, more responsive, and more maintainable code.</p><h3><strong>Open-Source Example App</strong></h3><p>To help you get started quickly, I’ve published a <strong>SwiftUI example app</strong> demonstrating a custom Combine publisher and subscriber for parallel image downloading. It shows how to integrate Swift’s structured concurrency (Task and withTaskGroup) with Combine’s publisher–subscriber model, plus some basic strategies for managing backpressure. You can check out the complete source code on GitHub:</p><p><a href="https://github.com/batuhangundogdu/CombineCustomPublishers">CombineCustomPublishers example on GitHub</a></p><p>Feel free to clone the project, experiment with the code, and adapt it for your own use cases</p><p><em>Happy Coding !</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c136193b3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Swift Developer’s Guide to Caching: Faster Data, Fewer Headaches]]></title>
            <link>https://medium.com/@batuhangundogdu/a-swift-developers-guide-to-caching-faster-data-fewer-headaches-8c9f3ba70b5e?source=rss-39004c7fdb32------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c9f3ba70b5e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Batuhan Gundogdu]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 13:31:38 GMT</pubDate>
            <atom:updated>2025-02-07T13:31:38.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K2bWvy4qJDz39Uw5" /><figcaption>Photo by <a href="https://unsplash.com/@robertbye?utm_source=medium&amp;utm_medium=referral">Robert Bye</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever had that moment where your app is gasping for air under network load or repetitive computations? Enter caching — your new best friend when you want speedier data access. But, as with any good friend, it comes with quirks you can’t ignore. Take concurrency, for instance: one moment your cache is sailing smoothly, then multiple threads swarm in, and you’ve got data corruption chaos.</p><p>No need to panic. Let’s unravel caching in Swift with a focus on concurrency smarts. We’ll explore the two major stars — in-memory and disk caching — discuss concurrency pitfalls, showcase barrier writes, and then wrap it all up with best practices (so you can sleep at night). Let’s dig in.</p><h4><strong>Table of Contents</strong></h4><ol><li>Caching in Swift: Why Bother?</li><li>In-Memory Caching: The Quick but Impermanent Star</li><li>Disk-Based Caching: Slower but Reliable</li><li>Concurrency Trouble: When Threads Attack</li><li>Barrier Writes: Our Concurrency Bodyguard</li><li>Thread-Safe Cache Implementations</li><li>Cache Invalidation: Banishing Stale Data</li><li>Practical Tips for Real Apps</li><li>Key Takeaways</li></ol><h3><strong>1. Caching in Swift: Why Bother?</strong></h3><p>Imagine you’ve got a resource-intensive operation — maybe a hefty network call or an image processing task. Repeating it every time a user navigates or taps a button quickly becomes tedious (and might eat into the user’s data plan). Caching steps in to store results for quick retrieval later, making your app feel instantly more responsive.</p><p><strong>The Perks:</strong></p><ul><li><strong>Speed</strong>: Everything’s a little snappier when you skip round-trip network calls.</li><li><strong>Efficiency</strong>: Conserve battery and data usage by not fetching the same thing repeatedly.</li><li><strong>Better UX</strong>: Users love apps that feel instant.</li></ul><p><strong>The Pitfalls:</strong></p><ul><li><strong>Memory Footprint</strong>: Store too much in RAM, and you’ll get uninvited memory pressure or even app termination.</li><li><strong>Data Staleness</strong>: Cached data might become outdated, so you need a strategy to refresh or invalidate it.</li><li><strong>Concurrency Hazards</strong>: Multiple writes without synchronization can lead to weird, hard-to-diagnose bugs.</li></ul><h3><strong>2. In-Memory Caching: The Quick but Impermanent Star</strong></h3><p>Think of in-memory caching like a high-speed sports car. It’s all about performance — reads and writes are nearly instantaneous. But if you close the app (or the OS needs more memory), your cached goodies vanish. That’s because they live in RAM, a realm of fast but volatile storage.</p><p><strong>Pros</strong></p><ul><li><strong>Lightning-Fast Access</strong>: Direct lookups in a dictionary or cache structure.</li><li><strong>Less Overhead</strong>: No file reads, no disc writes.</li></ul><p><strong>Cons</strong></p><ul><li><strong>Volatile</strong>: Data is lost when the app exits or the OS evicts your app from memory.</li><li><strong>Limited Capacity</strong>: RAM is precious; storing massive data could push your app to memory warnings.</li></ul><p><strong>Common Use Cases</strong></p><ul><li><strong>Small, frequently accessed data</strong> (like user settings that refresh every session).</li><li><strong>Intermediate results</strong> that don’t need to persist across app launches.</li><li><strong>Transient data</strong> — stuff that can be recalculated or refetched quickly if needed.</li></ul><h3><strong>3. Disk-Based Caching: Slower but Reliable</strong></h3><p>Need to hold onto something beyond the current app session or device reboot? Disk-based caching has your back. It’s not as agile as in-memory (file reads and writes are slower), but it offers persistence and roomier storage.</p><p><strong>Pros</strong></p><ul><li><strong>Persistent</strong>: Data lives on disk, so it’s still around tomorrow (unless you wipe it).</li><li><strong>Scalable</strong>: Typically can store more data without immediately hogging RAM.</li></ul><p><strong>Cons</strong></p><ul><li><strong>Slower Access</strong>: Reading and writing to disk is inherently more time-consuming.</li><li><strong>Potential File I/O Errors</strong>: Permissions or disk full scenarios need handling.</li></ul><p><strong>Common Use Cases</strong></p><ul><li><strong>Images, large JSON documents, or media</strong> that don’t fit well in memory.</li><li><strong>Offline modes</strong>, where preserving data across app restarts is essential.</li><li><strong>Download caches</strong> for bigger files or resources.</li></ul><h3><strong>4. Concurrency Trouble: When Threads Attack</strong></h3><p>Let’s face it: your Swift code probably deals with multiple threads or tasks these days. If you have a naive implementation of “just store data in a dictionary,” you’ll quickly hit issues if two threads write simultaneously (or if you read halfway through a write).</p><p><strong>Typical Cringe-Worthy Scenarios:</strong></p><ul><li><strong>Overwriting</strong>: A second write stomps over the first write’s changes.</li><li><strong>Inconsistent Reads</strong>: Data might be partially updated, leading to weird states.</li><li><strong>Random Crashes</strong>: Corrupted data or partially written files can set your app on fire.</li></ul><h3><strong>5. Barrier Writes: Our Concurrency Bodyguard</strong></h3><p>Before you reach for the painkillers, know that Swift’s Grand Central Dispatch offers a concurrency hack that’s as elegant as it is powerful: <strong>barrier writes</strong>. A barrier write on a concurrent queue ensures that while any piece of code is writing, no other reads or writes can sneak in.</p><p><strong>How It Works</strong></p><ol><li><strong>Concurrent Queue</strong>: Everyone can read freely in parallel, which is efficient if your app does more reads than writes.</li><li><strong>Barrier Flag</strong>: When you want to write, you use `async(flags: .barrier)` to block other reads/writes until it’s finished.</li></ol><p>This model is perfect if you prefer a read-heavy approach without sacrificing safety for writes.</p><h3><strong>6. Thread-Safe Cache Implementations</strong></h3><p>Now that we’ve set the stage, let’s jump into some real code. We’ll start with an in-memory example, then tackle disk-based caching.</p><h4><strong>6.1 In-Memory Example</strong></h4><pre>import Foundation<br><br>class SynchronizedMemoryCache&lt;Key: Hashable, Value&gt; {<br>    private let queue = DispatchQueue(label: &quot;com.example.memoryCache&quot;, attributes: .concurrent)<br>    private var storage: [Key: Value] = [:]<br>    <br>    func get(_ key: Key) -&gt; Value? {<br>        var result: Value?<br>        queue.sync {<br>            result = storage[key]<br>        }<br>        return result<br>    }<br>    <br>    func set(_ value: Value, for key: Key) {<br>        queue.async(flags: .barrier) {<br>            self.storage[key] = value<br>        }<br>    }<br>    <br>    func remove(_ key: Key) {<br>        queue.async(flags: .barrier) {<br>            self.storage.removeValue(forKey: key)<br>        }<br>    }<br>    <br>    func removeAll() {<br>        queue.async(flags: .barrier) {<br>            self.storage.removeAll()<br>        }<br>    }<br>}</pre><ul><li><strong>queue.sync for reads</strong>: Everyone can read concurrently, but the .sync call ensures the reading thread waits until it’s done.</li><li><strong>queue.async(flags: .barrier) for writes</strong>: Only one write can happen at a time, preventing collisions.</li></ul><p>This pattern is ideal if you’re reading often and writing less frequently. For maximum performance, keep your code in the read closures super light.</p><h4><strong>6.2 Disk-Based Example</strong></h4><pre>import Foundation<br><br>class SynchronizedDiskCache {<br>    private let queue = DispatchQueue(label: &quot;com.example.diskCache&quot;, attributes: .concurrent)<br>    private let fileManager = FileManager.default<br>    private let cacheDirectory: URL<br>    <br>    init?(folderName: String = &quot;MyDiskCache&quot;) {<br>        do {<br>            let dirs = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)<br>            guard let cacheURL = dirs.first?.appendingPathComponent(folderName) else {<br>                return nil<br>            }<br>            cacheDirectory = cacheURL<br>            <br>            if !fileManager.fileExists(atPath: cacheDirectory.path) {<br>                try fileManager.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)<br>            }<br>        } catch {<br>            print(&quot;Failed to create disk cache directory: \(error)&quot;)<br>            return nil<br>        }<br>    }<br>    <br>    func getData(forKey key: String) -&gt; Data? {<br>        var data: Data?<br>        queue.sync {<br>            let fileURL = cacheDirectory.appendingPathComponent(key)<br>            data = try? Data(contentsOf: fileURL)<br>        }<br>        return data<br>    }<br>    <br>    func setData(_ data: Data, forKey key: String) {<br>        queue.async(flags: .barrier) {<br>            let fileURL = self.cacheDirectory.appendingPathComponent(key)<br>            do {<br>                // .atomic ensures a complete write or none at all<br>                try data.write(to: fileURL, options: .atomic)<br>            } catch {<br>                print(&quot;Failed to write data for key \(key): \(error)&quot;)<br>            }<br>        }<br>    }<br>    <br>    func removeData(forKey key: String) {<br>        queue.async(flags: .barrier) {<br>            let fileURL = self.cacheDirectory.appendingPathComponent(key)<br>            try? self.fileManager.removeItem(at: fileURL)<br>        }<br>    }<br>    <br>    func removeAll() {<br>        queue.async(flags: .barrier) {<br>            let files = (try? self.fileManager.contentsOfDirectory(at: self.cacheDirectory,<br>                                                                   includingPropertiesForKeys: nil)) ?? []<br>            for file in files {<br>                try? self.fileManager.removeItem(at: file)<br>            }<br>        }<br>    }<br>}</pre><ul><li><strong>Disk Writes</strong>: Slower than memory, so definitely keep them off the main thread if possible.</li><li><strong>options: .atomic</strong>: Ensures you either write the entire file or nothing, avoiding partial corruption.</li><li><strong>Error Handling</strong>: Disk operations can fail for reasons like low storage, read-only file system, or OS constraints.</li></ul><h3><strong>7. Cache Invalidation: Banishing Stale Data</strong></h3><p>What happens when your data’s old news? Without an invalidation plan, your app might serve outdated information — or hog memory/disk indefinitely.</p><h4><strong>Approaches to Try</strong></h4><ol><li><strong>Time-Based : </strong>Keep a timestamp for each entry. If it’s beyond a certain age, toss it or refresh it.</li><li><strong>Size-Based : </strong>Particularly for large data, you might define a maximum size. When you exceed it, remove the least recently used items.</li><li><strong>Manual Purging : </strong>For sensitive or session-related data, explicitly remove entries when they become obsolete.</li><li><strong>App Lifecycle Hooks : </strong>Trigger cleanup on app background/termination events if certain resources are no longer necessary.</li></ol><h3><strong>8. Practical Tips for Real Apps</strong></h3><p>Now that we’ve walked through some sample code, let’s chat about how to make these caches shine in real projects.</p><ol><li><strong>Sync vs. Async : </strong>For something small like a user preference, synchronous reads might be fine.For bigger data or when on the main thread, asynchronous disk operations prevent UI freezes.</li><li><strong>Choose Wisely : </strong>If you see frequent lookups but minimal data, an in-memory cache might be the simplest route. If you deal with large files or need data after restarts, disk is your friend.</li><li><strong>Swift Concurrency : </strong>Swift’s async/await or actors can also help manage concurrency. You’d still need barrier-like logic if multiple tasks can modify shared state.</li><li><strong>Testing Is Your Ally : </strong>Throw concurrency tests at your cache, simulating heavy read/write loads. Race conditions usually show up under pressure.</li><li><strong>Analytics : </strong>Keep an eye on memory usage and disk footprints. Tools like Instruments or OSLog can highlight leaks or runaway storage.</li></ol><h3><strong>9. Key Takeaways (</strong>TL;DR<strong>)</strong></h3><ol><li><strong>Caching = Speed, But with Caveats</strong>: Done right, your app gets a real performance boost. Done wrong, you’ll wrestle with stale data and concurrency nightmares.</li><li><strong>In-Memory vs. Disk</strong>: Pick the right tool for the job. RAM for speed, disk for persistence.</li><li><strong>Concurrency Control Is Non-Negotiable</strong>: Barrier writes on a concurrent queue help you avoid race conditions with minimal overhead.</li><li><strong>Invalidation Matters</strong>: Without a strategy to remove or refresh old data, your cache can grow or serve useless entries.</li><li><strong>Always Test Under Load</strong>: Caches often behave fine until multiple tasks hammer them at once.</li></ol><h3><strong>Wrapping Up</strong></h3><p>Caching can be a lifesaver for performance — just be sure you’re aware of the concurrency gremlins lurking around. By pairing an in-memory approach for immediate reads with a disk-based fallback for persistence (and giving both a concurrency safety net), you get the best of both worlds.</p><p>Take the time to plan how data is added, read, and removed; then integrate your concurrency approach (barrier writes or Swift concurrency features) to ensure data integrity. When you have a solid invalidation plan, you’ll avoid that dreaded “junk drawer” phenomenon. The payoff? Speedy load times, happy users, and an app that’s robust even under heavy use.</p><p><strong>That’s it!</strong> With these concepts in your toolbox, you can confidently design a Swift cache system that’s fast, safe, and ready for the real world. Enjoy your smoother, speedier apps — and don’t forget to purge the old stuff once in a while!</p><p><em>Happy caching!</em></p><ul><li>Keep an eye on memory usage and disk footprints. Tools like Instruments or OSLog can highlight leaks or runaway storage.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c9f3ba70b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Static Over Singleton? A Memory Management Deep Dive in Swift]]></title>
            <link>https://medium.com/@batuhangundogdu/why-static-over-singleton-a-memory-management-deep-dive-in-swift-6637f51e5f54?source=rss-39004c7fdb32------2</link>
            <guid isPermaLink="false">https://medium.com/p/6637f51e5f54</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Batuhan Gundogdu]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 13:02:36 GMT</pubDate>
            <atom:updated>2025-02-07T12:27:02.693Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Hidden Costs of Your Beloved Singleton Pattern</h3><p>Remember that singleton you just wrote? The one with the classic <strong>static let shared = MyClass() </strong>? While it’s been our trusty companion for years, it might be time to reconsider our relationship with this pattern, especially when it comes to memory management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mkxq5OG0mzPMo8CN" /><figcaption>Photo by <a href="https://unsplash.com/@pietrozj?utm_source=medium&amp;utm_medium=referral">Pietro Jeng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s peek under the hood and see what’s really happening with our memory when we use these patterns. Trust me, you might be surprised by what we find.</p><h3>The Memory Footprint You Didn’t Know About</h3><p>First, let’s look at that familiar singleton implementation we all know and love:</p><pre>class AnalyticsManager {<br>    static let shared = AnalyticsManager() // Seems innocent, right?<br>    <br>    private var events: [Event] = []       // Always there, always watching<br>    private var configuration: Config      // Never letting go<br>    private var networkClient: Client      // Holding strong forever<br>    <br>    private init() {<br>        configuration = Config()<br>        networkClient = Client()<br>        // Welcome to permanent memory residence!<br>    }<br>}</pre><p>Here’s what’s really happening behind that innocent-looking code:</p><ol><li>Your singleton instance? It’s moving into your app’s memory and never moving out</li><li>All those properties? They’re like permanent residents in your heap</li><li>That memory? It’s locked in until your app decides to call it a day</li></ol><h3>The Static Alternative: A Breath of Fresh (Memory) Air</h3><p>Now, let’s look at a more memory-conscious approach:</p><pre>class AnalyticsManager {<br>    // No permanent residents here<br>    private static var events: [Event]?<br>    private static var configuration: Config?<br>    private static var networkClient: Client?<br>    <br>    static func track(_ event: Event) {<br>        // Only setting up camp when needed<br>        setupIfNeeded()<br>        events?.append(event)<br>    }<br>    <br>    static func cleanupIfNeeded() {<br>        // Free to pack up and leave when done<br>        events = nil<br>        configuration = nil<br>        networkClient = nil<br>    }<br>}</pre><p>See what we did there? Instead of permanent memory residents, we’ve got flexible temporary workers. They come when needed and leave when they’re done. Now that’s efficient memory management!</p><h3>The Real-World Impact</h3><p>Let’s look at a more complex example where memory really matters:</p><pre>// Your typical singleton media processor<br>class MediaProcessor {<br>    static let shared = MediaProcessor()<br>    <br>    private var processingQueue: OperationQueue<br>    private var imageCache: NSCache&lt;NSString, UIImage&gt;<br>    private var activeOperations: [String: Operation]<br>    <br>    private init() {<br>        processingQueue = OperationQueue()<br>        imageCache = NSCache()<br>        activeOperations = [:]<br>        // Congratulations! You&#39;re now carrying all this baggage all the time<br>    }<br>}<br><br>// Our memory-conscious static approach<br>class MediaProcessor {<br>    private static var processingQueue: OperationQueue?<br>    private static var imageCache: NSCache&lt;NSString, UIImage&gt;?<br>    private static var activeOperations: [String: Operation]?<br>    <br>    static func processMedia(_ media: Media) {<br>        // Setting up just what we need, when we need it<br>        if processingQueue == nil {<br>            processingQueue = OperationQueue()<br>            imageCache = NSCache()<br>            activeOperations = [:]<br>        }<br>        <br>        // Do the work<br>        <br>        // And here&#39;s the magic - we can clean up when we&#39;re done<br>        if noMoreProcessingNeeded {<br>            cleanupResources()<br>        }<br>    }<br>}</pre><h3>But Wait, Singletons Aren’t All Bad!</h3><p>Now, before you go refactoring all your singletons (put down that keyboard!), let’s talk about when your trusty singleton pattern is actually the right choice:</p><pre>class UserSessionManager {<br>    static let shared = UserSessionManager()<br>    private var currentUser: User?<br>    private var authToken: String?<br>    <br>    // This actually makes sense as a singleton because:<br>    // 1. We need consistent state across the app<br>    // 2. We want a single source of truth<br>    // 3. The memory footprint is minimal<br>    // 4. The lifecycle matches the app&#39;s lifecycle<br>}</pre><h3>The Memory Management Showdown</h3><p>Let’s compare how both approaches handle memory in different scenarios:</p><h4>Heavy Resource Management</h4><pre>// Singleton: The &quot;Always Ready&quot; Approach<br>class ImageProcessor {<br>    static let shared = ImageProcessor()<br>    private var processingQueue = OperationQueue() // Always there<br>    private var imageCache = NSCache&lt;NSString, UIImage&gt;() // Taking up space<br>    <br>    // Your memory is committed, whether you&#39;re processing images or not<br>}<br><br>// Static: The &quot;Just in Time&quot; Approach<br>class ImageProcessor {<br>    private static var processingQueue: OperationQueue?<br>    private static var imageCache: NSCache&lt;NSString, UIImage&gt;?<br>    <br>    static func process(_ image: UIImage) {<br>        // Resources appear like magic when needed<br>        setupIfNeeded()<br>        // Do the work<br>        // And disappear when done<br>        cleanupIfPossible()<br>    }<br>}</pre><h3>Making the Right Choice</h3><p>Here’s your cheat sheet for choosing between static and singleton:</p><h4>Go Static When:</h4><ul><li>You’re handling heavy resources (images, video, data processing)</li><li>Memory pressure is a concern</li><li>Resources have a clear lifecycle</li><li>Operations are independent</li></ul><h4>Stick with Singleton When:</h4><ul><li>You need consistent app-wide state</li><li>The memory footprint is minimal</li><li>You’re managing authentication or user sessions</li><li>You need guaranteed resource coordination</li></ul><h3>The Bottom Line</h3><p>While our beloved singleton pattern has served us well, static methods often provide better memory management capabilities. They give us the power to control our resource lifecycle, optimize memory usage, and build more efficient apps. But remember — it’s not about abandoning singletons entirely. It’s about making conscious choices about our app’s memory management. Sometimes, a singleton is exactly what you need. Other times, a static approach might help your app shed some unnecessary memory weight. Choose wisely, and your app’s memory footprint will thank you!</p><p><em>Want to dive deeper into Swift memory management? Follow for more technical deep dives and iOS development insights!</em></p><p><strong><em>Happy coding!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6637f51e5f54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency Made Easy with Swift Actors]]></title>
            <link>https://medium.com/@batuhangundogdu/concurrency-made-easy-with-swift-actors-142f48e1b057?source=rss-39004c7fdb32------2</link>
            <guid isPermaLink="false">https://medium.com/p/142f48e1b057</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Batuhan Gundogdu]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 20:38:56 GMT</pubDate>
            <atom:updated>2025-02-07T12:29:02.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xkpHJwVdqJdToxC5" /><figcaption>Photo by <a href="https://unsplash.com/@lighttouchedphotography?utm_source=medium&amp;utm_medium=referral">Kevin Schmid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Asynchronous programming can be a challenging task, especially when it comes to handling concurrent tasks in a way that is efficient and doesn’t lead to race conditions or deadlocks. Luckily, Swift provides a solution to this problem through the use of actors.</p><p>In this tutorial, we’ll explore what actors are, how they work, and how you can use them to write safer and more efficient concurrent code.</p><h3>What are actors?</h3><p>Actors are a new concurrency feature introduced in Swift 5.5. They are a way of managing mutable state in a concurrent environment, by allowing you to define a protected area of code that can only be accessed by one task at a time. Actors work by serializing access to their state, which means that you can safely modify their internal state without worrying about race conditions or deadlocks.</p><p>Here’s a simple example of an actor:</p><pre>actor MyActor {<br>    var count = 0<br><br>    func increment() {<br>        count += 1<br>    }<br>}</pre><p>In this example, we define an actor called MyActor that has an internal state variable called count. We also define a method called increment that increments the count variable. Because MyActor is an actor, we can safely access and modify the count variable from multiple tasks without worrying about race conditions or deadlocks.</p><h3>How do actors work?</h3><p>Under the hood, actors work by serializing access to their state. When a task wants to access an actor’s state, it must first acquire a lock on the actor. If the lock is available, the task can proceed with its access to the actor’s state. If the lock is not available, the task is suspended until the lock becomes available.</p><p>When a task modifies an actor’s state, it does so in a protected area of code that is only accessible to the task that holds the lock. Once the task is finished modifying the state, it releases the lock, allowing other tasks to access the actor’s state.</p><h3>How to use actors</h3><p>To use an actor, you simply create an instance of the actor and call its methods as you would with any other object. The only difference is that you need to use the await keyword when calling a method on an actor.</p><p>Here’s an example:</p><pre>let myActor = MyActor()<br><br>Task {<br>    await myActor.increment()<br>}<br><br>Task {<br>    await myActor.increment()<br>}</pre><p>In this example, we create an instance of the MyActor actor and call its increment method from two different tasks. Because increment modifies the actor&#39;s internal state, we need to use the await keyword to ensure that each task has exclusive access to the actor while it&#39;s modifying its state.</p><h3>Benefits of using Actors</h3><p>Actors provide several benefits when it comes to concurrent programming in Swift. Here are some of the main advantages:</p><h4>Encapsulation of mutable state</h4><p>Actors encapsulate mutable state, which means that all state modifications are performed in a single location. This makes it much easier to reason about concurrency issues, as there are fewer places where race conditions can occur.</p><h4>Structured concurrency</h4><p>Actors enforce structured concurrency, which means that all concurrent access to mutable state is done through the Actor’s methods. This makes it much easier to reason about the flow of data through your code, as you can see exactly which methods are being called by each task.</p><h4>Thread safety</h4><p>Actors provide thread safety, which means that they prevent multiple tasks from accessing the same mutable state at the same time. This greatly reduces the chances of race conditions and other concurrency bugs.</p><h3>Conclusion</h3><p>In conclusion, actors are a powerful new feature in Swift that provide a safe and efficient way of managing mutable state in a concurrent environment. By serializing access to their state, actors eliminate race conditions and deadlocks, making it easier to write correct and efficient concurrent code.</p><p>I hope this tutorial has helped you understand what actors are and how to use them in your own projects. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=142f48e1b057" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js 2 ve VueFire ile Firebase kullanımı]]></title>
            <link>https://medium.com/@batuhangundogdu/vue-js-2-ve-vuefire-ile-firebase-kullan%C4%B1m%C4%B1-e1542047b62e?source=rss-39004c7fdb32------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1542047b62e</guid>
            <category><![CDATA[vuefire]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[türkçe]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Batuhan Gundogdu]]></dc:creator>
            <pubDate>Wed, 23 May 2018 16:51:14 GMT</pubDate>
            <atom:updated>2018-05-23T16:51:14.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3q9ZQ6Sv1VNfwjwo5JzAw.png" /></figure><p>Selam, bu yazımda Vue.js 2 framework’ü ve Google’ın Firebase Database’ini kullanarak bir web uygulamasının nasıl geliştirilebileceğinden bahsedeceğim.</p><p>Vue.js’i yüklememiş olanlar için : <a href="https://vuejs.org/v2/guide/installation.html">https://vuejs.org/v2/guide/installation.html</a></p><p>npm paket yöneticisi yüklememiş olanlar için : <a href="https://www.npmjs.com/get-npm">https://www.npmjs.com/get-npm</a></p><h3><strong>Vue.js Projesi Oluşturma</strong></h3><p>Terminal’den ;</p><pre>$ vue init webpack</pre><p>komutu ile yeni bir proje oluşturuyoruz. Bu aşamada vue size terminal üzerinden birkaç soru soracak. Bu ayarları default şekilde bırakabilir ya da istediğiniz gibi değiştirebilirsiniz. Sonrasında projemiz oluşuyor.</p><h3>Vue.js projesi ile Firebase Entegrasyonu</h3><p>Firebase ile haberleşmeyi <a href="https://github.com/vuejs/vuefire">VueFire</a> sağlıyor. Firebase ve VueFire’ı projenize eklemek için, projenizi içeren klasöre gidip, terminal’den ;</p><pre>$ npm install firebase vuefire --save</pre><p>komutunu çalıştırıyoruz. Ve npm bize gerekli olan paketleri getiriyor.</p><p>Sonrasında, projemizi bir text editöründe (Ben Visual Studio Code tercih ediyorum) açıp, <strong>/src/main.js </strong>konumundaki dosyaya;</p><pre>import VueFire from &#39;vuefire&#39;</pre><p>ve</p><pre>Vue.use(VueFire)</pre><p>komutlarını ekliyoruz. Şimdi de, firebase ile bağlantı sağlayacağız. Bunun için <strong>/src </strong>konumuna <strong>firebase.js </strong>adında bir dosya oluşturuyoruz. Bu dosya bizim uygulamamızın firebase ile iletişimini sağlayacak. Dosyanın içindeki firebase bağlantı ayarlarını bize firebase sağlıyor.</p><p>Oluşturduğumuz <strong>/src/firebase.js </strong>dosyasına ;</p><pre>import Firebase from &#39;firebase&#39;<br></pre><pre>  const firebaseApp = Firebase.initializeApp({</pre><pre>  apiKey: &#39;&#39;,</pre><pre>  authDomain: &#39;&#39;,</pre><pre>  databaseURL: &#39;&#39;,</pre><pre>  projectId: &#39;&#39;,</pre><pre>  storageBucket: &#39;&#39;,</pre><pre>  messagingSenderId: &#39;&#39;</pre><pre>  })</pre><pre>export const db = firebaseApp.database()</pre><p>kodlarını ekliyoruz. Kodlardaki boş kısımları firebase’ten almamız gerekiyor. Bunun için, <a href="https://console.firebase.google.com/">Firebase Console</a>’da, sol navigasyon’daki ayar çarkına basıp, Proje Ayarları kısmına ilerliyoruz. Alttaki 3 seçenek’ten <strong>Firebase’i web uygulamanıza ekleyin </strong>seçeneğine tıkladığımızda web uygulamamızda kullanabilmek üzere firebase projemizin ayarları önümüze geliyor. Burada yazan <strong>apiKey, authDomain, databaseURL, projectId, storageBucket </strong>ve<strong> messagingSenderId </strong>değerlerinin karşılıklarını kopyalayıp, <strong>/src/firebase.js </strong>dosyamızın içindeki karşılıklarına yapıştırıyoruz.</p><p>Artık Vue.js uygulamamız Firebase ile bağlanıp direkt olarak data okuyabilecek konuma geldi.</p><h3>Vue.js Projesi ile Firebase Kullanımı — Veri Okuma</h3><p>Terminal’den proje komumumuza gidip;</p><pre>npm run dev</pre><p>Komutunu çalıştırdığımızda, projemiz <a href="http://localhost:8080/"><strong>http://localhost:8080</strong></a><strong> </strong>adresinde hayata geçmiş oluyor. Tarayıcımızdan bu adresi açınca Vue.js logosu ve bir kaç link görüyoruz.</p><p>Şimdi, <strong>HelloWorld.vue</strong> dosyasını açıp <strong>&lt;/template&gt;</strong> tag’inin içindeki kısımları tamamen siliyoruz. Firebase’e yazma işlemi için bir adet form, Firebase’den okuma işlemi için de bir adet list ekleyeceğiz. Projemiz bootstrap komponentlerinden oluştuğu için <a href="https://getbootstrap.com/docs/4.1/components/">bu linkteki</a> komponentleri projemizde kullanabiliriz. <strong>&lt;/template&gt; </strong>tag’inin içinde bir<strong> &lt;/div&gt; </strong>oluşturup, içine bir adet input ve bir adet list ekliyoruz ;</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;input type=&quot;text&quot;&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Gönder&lt;/button&gt;<br>    &lt;br&gt;<br>    &lt;ul class=&quot;list-group&quot;&gt;<br>      &lt;li class=&quot;list-group-item&quot;&gt; Listedeki eleman &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Değişiklikleri kaydettiğimizde, yapılan değişiklikleri anında tarayıcımızda görebiliriz. Şu an bir input, bir tuş ve tek elemanı bulunan bir listemiz var. Listedeki data manuel olarak girilen bir data, ama biz bu listeyi firebase’den gelen data ile doldurmak istiyoruz. Bunun için Firebase Console’umuzu açıp şu şekilde bir database yapısı oluşturuyoruz ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgiHetp9TM4793ihRSLGXg.png" /><figcaption>Firebase örnek database yapısı</figcaption></figure><p>Artık verilerimizi okuyup kendi projemizde gösterebiliriz. Bunun için <strong>HelloWorld.vue </strong>dosyasını açıp <strong>&lt;/script&gt; </strong>tag’ine şu şekilde firebase’i import ediyoruz ve firebase database referansını alıyoruz ;</p><pre>&lt;script&gt;<br>import { db } from &#39;../firebase&#39;</pre><pre>export default {<br>  name: &#39;HelloWorld&#39;,<br>  firebase: {<br>    firdata: {<br>      source: db.ref(&#39;messages&#39;),<br>      cancelCallback (err) {<br>        console.error(err)<br>      }<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><p>Şimdi ise, <strong>&lt;/template&gt; </strong>tag’inin içine eklediğimiz list elemanına firebase’den aldığımız datayı bağlayacağız. Vue.js’in bize sağladığı kolaylık burada devreye giriyor. List elemanının içine firebase referansı veriyoruz ve işlem tamamlanmış oluyor. <strong>&lt;li&gt; </strong>elemanını aşağıdaki gibi düzenliyoruz ;</p><pre>&lt;li class=&quot;list-group-item&quot; v-for=&quot;data in firdata&quot; v-bind:data=&quot;data&quot; :key=&quot;data.id&quot;&gt; {{ data.text }} &lt;/li&gt;</pre><p>Değişiklikleri kaydettiğinizde, şu şekilde bir ekranla karşılaşacaksınız ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6TXsL3ENsEvjrFRnfwSCw.png" /></figure><p><strong>HelloWorld.vue dosyası’nın tamamı :</strong></p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;input type=&quot;text&quot;&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Gönder&lt;/button&gt;<br>    &lt;br&gt;<br>    &lt;ul class=&quot;list-group&quot;&gt;<br>      &lt;li class=&quot;list-group-item&quot; v-for=&quot;data in firdata&quot; v-bind:data=&quot;data&quot; :key=&quot;data.id&quot;&gt; {{ data.text }} &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>import { db } from &#39;../firebase&#39;</pre><pre>export default {<br>  name: &#39;HelloWorld&#39;,<br>  firebase: {<br>    firdata: {<br>      source: db.ref(&#39;messages&#39;),<br>      cancelCallback (err) {<br>        console.error(err)<br>      }<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><pre>&lt;style scoped&gt;<br>h1, h2 {<br>  font-weight: normal;<br>}</pre><pre>ul {<br>  list-style-type: none;<br>  padding: 0;<br>}</pre><pre>li {<br>  display: inline-block;<br>  margin: 0 10px;<br>}</pre><pre>a {<br>  color: #42b983;<br>}<br>&lt;/style&gt;</pre><p>Artık, list elemanımızın datası, gerçek zamanlı olarak firebase’den geliyor. Müthiş, değil mi ? Firebase’de değişiklik yapmayı denediğiniz zaman, değişiklikler projemize anında yansıyacaktır.</p><h3>Vue.js Projesi ile Firebase Kullanımı — Veri Yazma</h3><p>Şimdi, input ve button komponentlerine fonksiyonalite kazandıracağız. Projemiz üzerinden firebase’e data ekleyebileceğiz ve eklediğimiz datayı gerçek zamanlı olarak görüntüleyebileceğiz.</p><p>Bunu yapmak için, <strong>&lt;/script&gt; </strong>ve<strong> &lt;/template&gt; </strong>tag’lerine bir kaç ekleme yapıp şu şekilde düzenliyoruz ;</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;input type=&quot;text&quot; <strong>v-model=&quot;newMessage.text&quot;</strong>&gt;<br>    &lt;button type=&quot;submit&quot; <strong>v-on:click=&quot;gonder&quot;</strong>&gt;Gönder&lt;/button&gt;<br>    &lt;br&gt;<br>    &lt;ul class=&quot;list-group&quot;&gt;<br>      &lt;li class=&quot;list-group-item&quot; v-for=&quot;data in firdata&quot; v-bind:data=&quot;data&quot; :key=&quot;data.id&quot;&gt; {{ data.text }} &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>import { db } from &#39;../firebase&#39;</pre><pre>export default {<br>  name: &#39;HelloWorld&#39;,<br>  <strong>data () {<br>    return {<br>      newMessage: {<br>        text: &#39;&#39;<br>      }<br>    }<br>  },</strong><br>  <strong>methods: {<br>    gonder: function (e) {<br>      if (this.newMessage.text === &#39;&#39;) {<br>        return<br>      }<br>      e.preventDefault()<br>      db.ref(&#39;messages&#39;).push(this.newMessage)<br>      this.newMessage.text = &#39;&#39;<br>    }<br>  },</strong><br>  firebase: {<br>    firdata: {<br>      source: db.ref(&#39;messages&#39;),<br>      cancelCallback (err) {<br>        console.error(err)<br>      }<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><p><strong>v-model=&quot;newMessage.text&quot; </strong>: Burada, yeni oluşturulacak olan newMessage objemizin text özelliğini direkt olarak input objesine bağladık. Yani, input komponentine yazılacak olan herhangi bir yazı direkt olarak objemizin özelliği haline gelmiş olacak.</p><p><strong>v-on:click=”gonder : </strong>Burada, tuşa basıldığında hangi fonksiyonun çağılacağını belirledik. <em>Dikkat edilmesi gereken kısım, eğer fonksiyon </em><strong><em>parametre</em></strong><em> </em><strong><em>almıyor</em></strong><em> ise, çağırılırken </em><strong><em>parantez</em></strong><em> </em><strong><em>kullanılmaması</em></strong><em> gerektiğidir.</em></p><p><strong>methods </strong>elemanı içerisinde fonksiyonlar tanımlanır.</p><p>Artık, gönder tuşuna basıldığında gerçek zamanlı olarak firebase’e data yazan ve kendisini firebase’deki datalar ile güncelleyen bir sisteme sahibiz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1542047b62e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>