<?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 Schrodinger&#39;s Cat on Medium]]></title>
        <description><![CDATA[Stories by Schrodinger&#39;s Cat on Medium]]></description>
        <link>https://medium.com/@madishettimounika123?source=rss-3535d6612cda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RMPnT93sESGUHychTkHIGA.png</url>
            <title>Stories by Schrodinger&amp;#39;s Cat on Medium</title>
            <link>https://medium.com/@madishettimounika123?source=rss-3535d6612cda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:12:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madishettimounika123/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[Strategies to Test-drive network requests | URLProtocol — swift]]></title>
            <link>https://medium.com/@madishettimounika123/strategies-to-test-drive-network-requests-urlprotocol-swift-dcb230207bf4?source=rss-3535d6612cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcb230207bf4</guid>
            <category><![CDATA[url-loading-system]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[urlprotocol]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Schrodinger's Cat]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 08:50:17 GMT</pubDate>
            <atom:updated>2024-03-03T08:50:17.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strategies to Test-drive network requests | URLProtocol — swift</h3><p>Hi!</p><p>An ideal Test Suite is composed of a larger portion of Unit Tests, followed by Integration and UI Tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*Oods8HZRfN0LdkGaz4hWIw.jpeg" /><figcaption>Image Source Internet, added Text</figcaption></figure><p>Unit Tests deal with testing individual classes and methods(component-level testing), producing clear failure messages when we detect a problem. Unit Tests run quickly often in the order of 100s or 1000s of tests per minute. The speed is possible only if the external factors(network/db operations) influencing the Unit Tests are almost zero.</p><p>Now, Let’s discuss different approaches for test-driving code that has a dependency on the network.</p><h3><strong>1. End to End testing:</strong></h3><p>It’s a testing strategy that checks integration between client and server communication. A downside of end-to-end testing is that we need to talk to the external server, which requires a network connection. The tests can be flaky (fail unexpectedly), cannot cover all the scenarios, and can be slow (depending on network performance). Although this is a valid strategy, there are other fast and reliable techniques for testing at the component level. We can add end-to-end (integration) tests to guarantee correct communication between the client and the server.</p><h3>2. Mock URLSession:</h3><h4>a. Subclass:</h4><p>Test by subclassing and spying/mocking the <strong><em>URLSession</em></strong>. It can be faster and more reliable but we are not sure of the internal implementation of the URLSession, we inherently increase the risk by introducing the unknowns. Subclassing introduces tight coupling between the tests and the production code.</p><p>Below is the code snippet for subclassing and injection of a URLSession type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20cbb1cd592ef507426eb8a2cbb98e45/href">https://medium.com/media/20cbb1cd592ef507426eb8a2cbb98e45/href</a></iframe><h4>b. Protocol</h4><p>Another approach for testing the <strong><em>URLSession</em></strong> is to use protocols that mimic the desired interfaces we’d like to spy on.</p><p>Create a protocol <em>HTTPSession</em> with a signature the same as URLSession’s datatask. Inject an instance of type HTTPSession into your SUT. This way we improve the test code by removing unnecessary dependency on URLSession. But we still haven’t solved the tight coupling with the URLSession APIs since the protocols are mimicking its method signatures.</p><p>Additionally, by adding a set of protocols for testing the URLSession-based implementation, we introduce a lot of noise in our production code, as the protocols are created solely for testing purposes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d1d48b84b2d90fd5a96b0505f7e7555/href">https://medium.com/media/8d1d48b84b2d90fd5a96b0505f7e7555/href</a></iframe><h3>3. URLProtocol Stubbing:</h3><p>The least known technique for intercepting and testing network requests is with the URL Loading System and URLProtocol abstract class.</p><p>The URL Loading system provides a great hook for testing if the interaction with ULRSession APIs is correct or not. URLProtocol does the underlying work of opening a network connection, writing a request, and reading back a response. We can create a subclass of URLProtocol that just makes assertions for the requests that are coming out and provides mock responses. URLProtocol communicates the progress back to the system via URLProtocolClient protocol.</p><blockquote>URL Loading System:</blockquote><blockquote>Interact with URLs and communicate with servers using standard Internet protocols.</blockquote><blockquote>The URL Loading System provides access to resources identified by URLs, using standard protocols like https or custom protocols you create. Loading is performed asynchronously, so your app can remain responsive and handle incoming data or errors as they arrive.</blockquote><blockquote>— Apple</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfZpaLki2knvC_Ee6_eXNg.png" /></figure><p>Now we know the URL Loading system, How it is useful for Unit testing Network requests?</p><p>URL Loading System has an abstract class named URLProtocol( Yes, you heard it right. It’s an abstract class, not a protocol). This abstract class can be used to intercept outgoing requests and alter the URL loading behavior.</p><blockquote>URLProtocol: An abstract class that handles the loading of protocol-specific URL data. — Apple</blockquote><p>Apple recommends to not use the URLProtocol directly, subclass it, and then use it to intercept your requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roB5ZFZPJ-V7pjGe17VKeg.png" /><figcaption>Source: Apple</figcaption></figure><p>To activate or deactivate a custom URL loading behavior in the URL Loading System, we must register or unregister the custom <strong>URLProtocol</strong> subclass using the <strong>URLProtocol.registerClass(AnyClass)</strong> and <strong>URLProtocol.unregisterClass(AnyClass)</strong> methods.</p><p>When subclassing URLProtocol, you need to override a few methods of the URLProtocol:</p><pre>class func canInit(with:URLRequest) -&gt; Bool<br>class func canonicalRequest(for:URLRequest)<br>func startLoading()<br>func stopLoading()</pre><p>Subclassing URLProtocol is our preferred approach because-</p><ol><li>It’s fast and reliable.</li><li>It’s a documented and recommended API by Apple to test network requests, so it should not have any unexpected mocking behavior.</li><li>It helps us to decouple the tests from production implementation.</li><li>It helps us to hide test details from production code.</li></ol><p>Now, we understand with an example how the URLProtocol stubbing works-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4d4cf444a1795000ce1d53334a6c32b/href">https://medium.com/media/a4d4cf444a1795000ce1d53334a6c32b/href</a></iframe><p>There can also be different approaches for intercepting the network requests. Always choose the approach that fits your scenario.</p><p><strong><em>References-</em></strong></p><ul><li><a href="https://developer.apple.com/videos/play/wwdc2018/417">Testing Tips &amp; Tricks - WWDC18 - Videos - Apple Developer</a></li><li><a href="https://developer.apple.com/documentation/foundation/url_loading_system?language=objc">URL Loading System | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/foundation/nsurlprotocol?language=objc">NSURLProtocol | Apple Developer Documentation</a></li><li><a href="https://www.kodeco.com/2292-using-nsurlprotocol-with-swift">Using NSURLProtocol with Swift</a></li></ul><h3>Questions?</h3><p>Please feel free to comment below, <strong>if you have any questions.</strong></p><p>If you like this article, feel free to share it with your friends and leave me a comment.</p><p>Thanks for reading! 👨🏼‍💻</p><p>You can find me on: <a href="https://www.linkedin.com/in/mounika-madishetti-988a85152">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcb230207bf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Combine-Subscribers]]></title>
            <link>https://medium.com/@madishettimounika123/ios-combine-subscribers-086d6eb02000?source=rss-3535d6612cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/086d6eb02000</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Schrodinger's Cat]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 08:38:48 GMT</pubDate>
            <atom:updated>2024-03-02T08:38:48.972Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous articles, We discussed Introduction to Combine, <a href="https://medium.com/@madishettimounika123/combine-publishers-989786adfc92">Publishers</a> and <a href="https://medium.com/@madishettimounika123/combine-operators-220636d53b64">Operators</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riN6QnnIqpHSH3uXSCaY8A.png" /></figure><p>We now focus on Subscribers.</p><p>Subscribers are the last and the most fruitful characters in the story of Combine. Subscribers get to enjoy the yield of publishers and operators. They get to do something with the emitted values which can either be displaying on the screen or a network call..</p><p>Combine has 2 built-in subscribers- sink, assign</p><p><strong>sink</strong>: sink subscribers provide closures to receive output and completion.</p><pre>let just = Just(&quot;hello&quot;)<br>just.sink(receiveCompletion: {<br>    print(&quot;receive completion: &quot;, $0)<br>}, receiveValue: { val in<br>    print(&quot;value: \(val)&quot;)<br>})<br><br>/*<br>output: <br>value: hello<br>receive completion: finished<br>*/</pre><p><strong>assign</strong>: assign subscriber allows you to bind the value to some property on your data model or on a UIControl to display without needing to write extra logic.</p><pre>class SomeObject {<br>    var value: String = &quot;&quot; {<br>        didSet {<br>            print(&quot;value is&quot;, value)<br>        }<br>    }<br>}<br><br>let object = SomeObject()<br><br>let publisher = [&quot;hello&quot;, &quot;world&quot;].publisher<br>publisher.assign(to: \.value, on: object)<br><br>/*<br>output: <br>value is hello<br>value is world<br>*/</pre><p><strong>Memory Management of subscribers:</strong></p><p>When a subscriber finishes its work and no longer require to receive any events, We can cancel the subscription to free up the resources.</p><p>You don’t need to specifically manage memory of subscribers. Combine has a protocol AnyCancellable. sink and assign confirm to AnyCancellable.</p><blockquote>An <a href="https://developer.apple.com/documentation/combine/anycancellable">AnyCancellable</a> instance automatically calls <a href="https://developer.apple.com/documentation/combine/cancellable/cancel()">cancel()</a> when deinitialized.</blockquote><h3>Questions?</h3><p>Please feel free to comment below, <strong>if you have any questions.</strong></p><p>If you like this article, feel free to share it with your friends and leave me a comment.</p><p>Thanks for reading! 👨🏼‍💻</p><p>You can find me on: <a href="https://www.linkedin.com/in/mounika-madishetti-988a85152">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=086d6eb02000" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine — Operators]]></title>
            <link>https://medium.com/@madishettimounika123/combine-operators-220636d53b64?source=rss-3535d6612cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/220636d53b64</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Schrodinger's Cat]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 16:14:44 GMT</pubDate>
            <atom:updated>2024-02-27T10:30:39.121Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Combine — Operators</h3><p>Hello!</p><p>The story of combine has 3 main characters- Publishers, Operators and Subscribers.</p><p>Before reading this article, access my previous article on <a href="https://medium.com/@madishettimounika123/combine-publishers-989786adfc92">publishers</a></p><p>In this article, we delve into the fundamental concepts of operators, their types and how they facilitate various operations on the publishers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4bOJGFTmORuB_-veTYD80g.png" /><figcaption>source: Internet</figcaption></figure><p>If you compare combine with any human language like English, operators are just like words. The more operators you know, the better you can articulate the logic and intention of your app.</p><p>Generally speaking, the publisher receives upstream events, the operator manipulate the events, and then sends the manipulated events downstream to consumers(subscribers).</p><p>Operators sit between Publishers and Subscribers. Each operator is of type Publisher. Operators are generally built using the builder design pattern, having <strong>composable</strong> structure to have more elegant looking dot syntax(same as how <a href="https://developer.apple.com/documentation/swiftui/viewmodifier">view modifiers</a> work in SwiftUI).</p><p>Operators are classified into few types based on the type of operations they perform-</p><ol><li><em>Transforming Operators</em></li><li><em>Filtering Operators</em></li><li><em>Combining Operators</em></li><li><em>Time manipulation Operators</em></li><li><em>Sequence Operators</em></li></ol><blockquote><strong>Transforming Operators:</strong></blockquote><blockquote>Transforming operators helps to manipulate the published events. These operators are similar to few higher orderer functions in swift(map, trymap, flatmap, maperror, compactmap, trycompactmap)</blockquote><h3>map(_:):</h3><p>map works similar to swift map except that it works on published events. It receives incoming events and performs operations on those. Below is the marble diagram:</p><figure><img alt="marble diagram for map operator which takes incoming events and mutliply each with a 2" src="https://cdn-images-1.medium.com/max/1024/1*qD9k3GJx2DHoZpDLHOq_RA.png" /><figcaption>source: kodeco</figcaption></figure><pre>var subscriptions = Set&lt;AnyCancellable&gt;()<br><br>[123, 4, 56].publisher<br>    .map { $0 * 2 }<br>    .sink(receiveValue: { print($0) })<br>    .store(in: &amp;subscriptions)<br><br>output: <br>246<br>8<br>112</pre><h3>tryMap(_:)</h3><p>tryMap is similar to map but throws an error.</p><pre>[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;hello&quot;, &quot;5&quot;].publisher<br>    .tryMap { try Int($0) }<br>    .sink(receiveCompletion: { print($0) },<br>          receiveValue: { print($0) })<br>    .store(in: &amp;subscriptions)</pre><h3>flatMap(maxPublishers:_:)</h3><p>The flatMap operator flattens multiple upstream publishers into a single downstream publisher — or more specifically, flatten the emissions from those publishers.</p><p>The publisher returned by flatMap may not be of the same type as the upstream publishers it receives.</p><blockquote><strong>2. Filtering Operators</strong></blockquote><blockquote>In the previous section we have seen transforming operators, But what happens when you want to limit the values or events emitted by the publisher, and only consume <em>some</em> of them? <em>Filters</em> are used in this context.</blockquote><h3>filter(_:):</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gp8LhM3P8U5iKTAAJpSZhw.png" /><figcaption>source: kodeco</figcaption></figure><pre>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].publisher<br>    .filter { $0.isMultiple(of: 3) }<br>    .sink(receiveValue: { n in<br>        print(&quot;\(n) is a multiple of 3!&quot;)<br>    })<br>    .store(in: &amp;subscriptions)<br><br>// output-<br>3 is a mulitple of 3!<br>6 is a mulitple of 3!<br>9 is a mulitple of 3!</pre><blockquote><strong>3. Combining Operators</strong></blockquote><p>Now that we learnt how transforming and filtering operators work, we know how operators work, how they manipulate the upstream and how to use them to construct logical publisher chains from your data.</p><p>Combine operators lets us combine events emitted by 2 or more publishers and create meaningful combinations of data in your Combine code.</p><h3>prepend(Output…)</h3><p>preprend operator appends the events to the beginning of the stream of incoming events. The appended events should be of same type as incoming events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8hygXMWnqX30iNol4KBjg.png" /><figcaption>source: kodeco</figcaption></figure><pre>[3, 4].publisher<br>    .prepend(1, 2)<br>    .sink(receiveValue: { print($0) })<br>    .store(in: &amp;subscriptions)<br><br>// output:<br>1<br>2<br>3<br>4</pre><p><strong>append(Output…)</strong></p><p>append operator works similar to prepend, but appends at the end of incoming stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6vLWfg9IJ_fE0ZKzqtBgA.png" /><figcaption>source: kodeco</figcaption></figure><pre>[1].publisher<br>    .append(2, 3)<br>    .append(4)<br>    .sink(receiveValue: { print($0) })<br>    .store(in: &amp;subscriptions)<br><br>// output-<br>1<br>2<br>3<br>4</pre><blockquote><strong>4. Time Manipulation Operators</strong></blockquote><p>Timing is everything. The core idea behind reactive programming is to model asynchronous event flow <em>over time</em>. In this respect, the Combine framework provides a range of operators that allow you to deal with time.</p><blockquote><strong>5. <em>Sequence Operators</em></strong></blockquote><blockquote>Sequence operators work on the entire sequence of the incoming stream instead of individual event in the stream.</blockquote><h3>min</h3><p>The min operator helps to find the minimum value in a stream of events. It’s a greedy operator and must wait for the publisher’s <em>.finished</em> completion only then it performs min operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6kQJG9qh9WJcvgJAw3LvA.png" /><figcaption>source: kodeco</figcaption></figure><pre>[1, -50, 246, 0].publisher<br>    .min()<br>    .sink(receiveValue: { print(&quot;Lowest value is \($0)&quot;) })<br>    .store(in: &amp;subscriptions)<br><br>// output -<br>Lowest value is -50</pre><h3>max</h3><p><em>max</em> works exactly like <em>min</em>, except that it finds the <em>maximum</em> value emitted by a publisher.</p><p>That’s all about Combine Operators. Will include subscribers in the next article.</p><h3><strong><em>References:</em></strong></h3><ul><li><a href="https://www.kodeco.com/books/combine-asynchronous-programming-with-swift/v4.0/">Combine: Asynchronous Programming With Swift</a></li><li><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></li></ul><h3>Questions?</h3><p>Please feel free to comment below, <strong>if you have any questions.</strong></p><p>If you like this article, feel free to share it with your friends and leave me a comment.</p><p>Thanks for reading! 👨🏼‍💻</p><p>You can find me on: <a href="https://www.linkedin.com/in/mounika-madishetti-988a85152">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=220636d53b64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine — Publishers]]></title>
            <link>https://medium.com/@madishettimounika123/combine-publishers-989786adfc92?source=rss-3535d6612cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/989786adfc92</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine]]></category>
            <dc:creator><![CDATA[Schrodinger's Cat]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 16:40:40 GMT</pubDate>
            <atom:updated>2024-03-02T08:22:10.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Combine — Publishers</h3><p>With synchronous coding, You always know the current state of the data in your app. The predictability of the order of execution is a little complex with async programming.</p><p>Apple has evolved a lot with async coding. NSThread, KVO KVC, Notification Center, delegates, closure/callback, async/await.</p><p>Combine is a declarative approach to handling async code. Apple gave the flexibility of writing reactive code with an in-house framework rather than depending on 3rd party frameworks(RxSwift/ReactorKit).</p><p>Combine APIs make many of the classic async problems fairly easy to solve.</p><figure><img alt="marble diagram" src="https://cdn-images-1.medium.com/max/807/1*_qdHqWENjy031-zq0yR9yw.jpeg" /><figcaption>source: internet</figcaption></figure><p>The story of Combine has 3 important characters- Publishers, Operators, and Subscribers.</p><p><em>Short Story:</em></p><p><em>The publisher sends Data. Operators can modify the data. The Subscribers get the modified data.</em></p><p>Limiting the scope of this article to Publishers.</p><p><strong>Publishers-</strong></p><p>A publisher can have 0/more Operators and 1/more subscribers. Publisher emits events only when there’s an active subscriber listening. Publishers emit any of these 3 types of event</p><ol><li>Output</li><li>Success completion</li><li>Failure Completion</li></ol><p>Publisher stops emitting after a successful/failure completion.</p><blockquote>Each publisher confirms to ‘Publisher’ protocol with 2 associated types.</blockquote><blockquote>1. Publisher.Output: Output is the type of value the publisher emits. If it is an Int publisher, It can never emit String or other Date type values.</blockquote><blockquote>2. Publisher.Failure: Failure is the type of error the publisher throws when it fails. If the Publisher never fails, use <strong><em>Never</em></strong> failure type.</blockquote><p><strong>Just</strong>: A publisher that can emit only a single event to each of its subscribers and then finishes.</p><pre>Just(&quot;Hello World&quot;)</pre><p><strong>Future&lt;Output, Error&gt;</strong>: Not a lazy publisher, executes as soon as it’s created. A Future publishes an event or an error by invoking a closure(Promise).</p><pre>Future&lt;Int, Never&gt;() { promise in <br>DispatchQueue.global().asyncAfter(deadline: .now() + 3) {<br>    promise(.success(1))<br>  }<br>}</pre><p><strong>Subject: </strong>A subject is a way to bridge imperative code to the declarative world of Combine.</p><p><strong>PassthroughSubject&lt;Output, Error&gt;:</strong> PassthroughSubject enables you to send events on demand. They pass values and a completion event.</p><pre>let subject = PassthroughSubject&lt;Int, Never&gt;()<br>subject.send(1)<br>subject.send(2)<br>subject.send(completion: .finished)</pre><p><strong>CurrentValueSubject&lt;Output, Error&gt;: </strong>CurrentValueSubject has an initial value associated with it. New subscribers immediately get that value or the latest value published by that subject.</p><pre>  let subject = CurrentValueSubject&lt;Int, Never&gt;(0)<br>  subject.send(1)<br>  subject.value = 2 // also publishes the data</pre><p><strong>Timer:</strong> with timer, you can emit at regular intervals</p><pre>let timer = Timer.publish(every: 1.0, on: .main, in: .default)</pre><p><strong>Sequence:</strong> Use this publisher, when you want to make a series of elements reactive.</p><pre>let publisher = [1,2,3,4].publisher</pre><p><strong>Record:</strong> to record a series of events for testing purposes, or if you ever need multiple subscribers to carry out the same order of events</p><pre>let publisher = Record&lt;Int, Never&gt; (output: [1,2,3], completion: .finished)</pre><p><strong>Deferred:</strong> Used when we want to create publisher only after the first subscriber subscribes. Useful when creating a publisher is a heavy task, create it only if needed.</p><pre>let publisher = Deferred {<br>return Just(&quot;hello&quot;)<br>}</pre><p><strong>Empty:</strong> This publisher will never emit values, emits only completion.</p><pre>let publisher = Empty&lt;Int, Never&gt;()</pre><p><strong>Fail:</strong> A fail won’t emit values. It will only emit a failure/completion with error. Useful to manually catch error in functions that could return any other type of publisher.</p><pre>let publisher = Fail&lt;String, ResponseError&gt;(error: .nonetwork)</pre><p><strong>Type Erasure:</strong></p><p>There will be times when you want to let subscribers subscribe to receive events from a publisher without accessing additional details about that publisher.</p><p>This can be done with type erased publisher.</p><pre>let subject = PassthroughSubject&lt;Int, Never&gt;() <br>let publisher = subject.eraseToAnyPublisher() // the publisher is of type AnyPublisher&lt;Int, Never&gt;.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=989786adfc92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[what’s the issue with DispatchQueue.main.sync inside DispatchQueue.main.async?]]></title>
            <link>https://medium.com/@madishettimounika123/whats-the-issue-with-dispatchqueue-main-sync-inside-dispatchqueue-main-async-34093e9dc19a?source=rss-3535d6612cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/34093e9dc19a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[main-thread]]></category>
            <dc:creator><![CDATA[Schrodinger's Cat]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 17:14:08 GMT</pubDate>
            <atom:updated>2023-02-02T17:14:08.047Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we answer the question, let’s get familiarised with DispatchQueues, sync, and async tasks —</p><p>DispatchQueue:</p><p>Generally, concurrent execution happens in different CPU cores by creating multiple threads. Creating these threads and managing them is a difficult task for a developer. Apple made developer’s life a little better by introducing dispatch queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmclevC7TrfEnFb-QvNj5A.jpeg" /><figcaption>source: Internet</figcaption></figure><p><strong>Dispatch Queues-</strong></p><ol><li>main dispatch queue</li><li>Global dispatch queue</li><li>Custom dispatch queue</li></ol><p><strong>main dispatch queue</strong>: tasks dispatched to this queue run on the main thread and execution is on a serial queue(first in first out)</p><pre>DispatchQueue.main.async {<br>  print(&quot;Hello, I am executing asynchronously on main thread&quot;)<br>}</pre><p>Global dispatch queue is a concurrent dispatch queue and is out of the scope of this article:D</p><p><strong>Synchronous</strong> <strong>Task</strong>:</p><p>When the control reaches a sync statement, it switches from the current task under execution to the sync task.</p><pre>let customQueue = DispatchQueue(label: &quot;custom_queue&quot;, attributes: .concurrent)<br>customQueue.async {<br>    print(&quot;hello&quot;)<br>    customQueue.sync {<br>        print(&quot;Welcome to&quot;)<br>    }<br>    print(&quot;the world of joy!&quot;)<br>}<br>//output: <br>hello<br>Welcome to<br>the world of joy!<br></pre><p><strong>Asynchronous</strong> <strong>Task:</strong></p><p>When control reaches an async task, it first completes the current task under execution and then switches to the async task.</p><pre>let customQueue = DispatchQueue(label: &quot;custom_queue&quot;)<br>customQueue.async {<br>    print(&quot;second&quot;)<br>}<br>print(&quot;first&quot;)<br>//output:<br>first<br>second</pre><p>Solution:</p><pre>//Assuming control is on main thread<br>//example:1 <br>  DispatchQueue.main.sync {<br>    print(&quot;hello&quot;)<br>  }<br><br>//runtime error: Execution was interrupted, reason: EXC_BREAKPOINT (code=1, subcode=0x18011d558).<br><br><br>//example:2<br>DispatchQueue.main.async {<br>    print(&quot;first&quot;)<br>    DispatchQueue.main.sync {<br>        print(&quot;second&quot;)<br>    }<br>    print(&quot;third&quot;)<br>}<br><br>//output: <br>hello <br>//and waits indefinitely for the sync task to get finished, sync on the otherhand waits for async to get finished, resulting in deadlock.</pre><p>In the above code snippet(example:2), the main is a serial queue, and tasks are executed in FIFO order. The async task will be at front of the queue and start executing it. When the control reaches the sync statement, It tries to execute the sync block. Since it’s a serial queue and the async task is still under execution, sync tasks wait for the async to complete execution. At the same time, async waits for sync to complete. There’s a deadlock situation where each task is waiting for the other and It results in a run time error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpOOlFQJts-SyBNqWwr35Q.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34093e9dc19a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement Higher Order Functions — Swift]]></title>
            <link>https://medium.com/@madishettimounika123/implement-higher-order-functions-swift-36884580a7b3?source=rss-3535d6612cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/36884580a7b3</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Schrodinger's Cat]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 10:32:25 GMT</pubDate>
            <atom:updated>2022-12-26T10:32:25.671Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implement Higher Order Functions — Swift</h3><p>Okay! so, It’s been a while since I wrote. Long Time, No See!🤪 Without much further ado, let’s get started!!</p><figure><img alt="Higher order thinking cat here" src="https://cdn-images-1.medium.com/max/600/1*eRSWiPQN-VEKc_yliRO79A.jpeg" /><figcaption>source: Internet</figcaption></figure><blockquote><strong><em>Higher Order Function:</em></strong></blockquote><blockquote>A function that accepts another function as an argument or it returns a function or it can do both. We are already aware of higher order functions which transform an array of elements.</blockquote><blockquote><a href="https://developer.apple.com/documentation/swift/array/map(_:)-87c4d">map</a>, <a href="https://developer.apple.com/documentation/swift/array/compactmap(_:)">compactMap</a>, <a href="https://developer.apple.com/documentation/swift/sequence/filter(_:)">filter</a>, <a href="https://developer.apple.com/documentation/swift/array/reduce(_:_:)">reduce</a>, <a href="https://developer.apple.com/documentation/swift/array/partition(by:)-90po8">partition</a> are the apple defined higher order functions.</blockquote><pre>let array: [Int] = [1, 2, 3, 4] <br>let newArray: [Int] = array.map { $0 * 2 } <br>print(newArray)<br>o/p: [2, 4, 6, 8]<br></pre><p>Okay, Now let’s write our own implementation for higher order functions</p><blockquote><strong>map</strong></blockquote><pre>extension Array {<br> func customMap&lt;T&gt;(completion: (Element) -&gt; T) -&gt; [T] {<br>        var res: [T] = []<br>        forEach { ele in<br>            let transformedEle = completion(ele)<br>            res.append(transformedEle)<br>        }<br>        return res<br>    }<br>}<br>let customMap = [1,2,3,4,5].customMap { (ele: Int) -&gt; Int  in return ele * 2 }<br>print(customMap)<br>op: 1, 4, 6, 16, 25</pre><blockquote><strong>compactMap</strong></blockquote><pre>extension Array {<br>    func customCompactMap&lt;T&gt;(completion: (Element) -&gt; T?) -&gt; [T] {<br>        var res: [T] = []<br>        forEach { ele in<br>            if  let transformedEle = completion(ele) {<br>                res.append(transformedEle)<br>            }<br>        }<br>        return res<br>    }<br>}<br>let customCompactMap = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;four&quot;].customCompactMap { (ele: String) -&gt; Int? in<br>    return Int(ele)<br>    <br>}<br>print(customCompactMap)<br>op: 1, 2, 3</pre><blockquote><strong>filter</strong></blockquote><pre>extension Array {<br>    func customFilter&lt;T&gt;(completion: @escaping (Element) -&gt; T?) -&gt; [T] {<br>        var res: [T] = []<br>        forEach { ele in<br>            if let e = completion(ele) {<br>                res.append(e)<br>            }<br>        }<br>        return res<br>    }<br>}<br>let customFilter = [1,3,4,5,6,7].customFilter { (ele: Int) -&gt; Int? in<br>    return ele % 2 == 0 ? ele : nil<br>}<br>print(customFilter) <br>op: 4, 6</pre><blockquote><strong>reduce</strong></blockquote><pre>extension Array {<br>    func customReduce&lt;T&gt;(initialResult: T, completion: @escaping (T, Element) -&gt; T) -&gt; T {<br>        var result = initialResult<br>        forEach { ele in<br>            result = completion(result, ele)<br>        }<br>        return result<br>    }<br>}<br>let customReduce = [1,2,3,4].customReduce(initialResult: 0) { (res: Int, ele: Int) -&gt; Int in<br>    return res + ele<br>}<br>print(customReduce)<br>op: 10</pre><ul><li><a href="https://medium.com/@madishettimounika123/weak-unowned-swift-9fc3b43760a0">Weak, unowned - swift</a></li><li><a href="https://medium.com/@madishettimounika123/capture-lists-in-swift-19142660703e">Capture Lists in Swift</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36884580a7b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Weak, unowned - swift]]></title>
            <link>https://medium.com/@madishettimounika123/weak-unowned-swift-9fc3b43760a0?source=rss-3535d6612cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fc3b43760a0</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[unowned]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[weak]]></category>
            <dc:creator><![CDATA[Schrodinger's Cat]]></dc:creator>
            <pubDate>Wed, 28 Jul 2021 06:01:42 GMT</pubDate>
            <atom:updated>2021-07-28T06:01:42.492Z</atom:updated>
            <content:encoded><![CDATA[<p>Fun yet True fact- You are a weak variable feels so much positive than you are a weak person. Let’s find out why!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*9p1iERvwUa9GAkw7BJjQ8Q.jpeg" /><figcaption>source: Internet</figcaption></figure><p>Strong references don’t allow the memory of an object to be deallocated until retain count becomes zero. But it’s not the case with weak and unowned references. If a variable is declared as weak or unowned, ARC doesn’t take these variables into retain count consideration.</p><p>When weak and unowned serve the same purpose of avoiding a strong reference cycle. why Apple introduced both of them. Let’s analyze!</p><p>Weak:</p><p>When the memory of an object the weak variable points to is deallocated, ARC’s duty is to set the weak variable to nil. Otherwise, a weak variable tries to access an object at the memory location which is not present. Here the value of the weak variable is changing from some value to nil. Hence, Weak should always be used with variables.</p><p>And ARC sets this weak reference to nil when the object it points to deallocates. Hence weak should be optional. The weak variable is safe as it deals with optionals.</p><p>Unowned-</p><p>Unowned references are also not considered in the ARCs retain count. But unowned references should always point to some memory location. If the object it points to is deallocated, it can lead to runtime errors and crashes.</p><p>Use unowned references only when you are aware that the class instance your unowned reference pointing will never be deallocated before.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fc3b43760a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capture Lists in Swift]]></title>
            <link>https://medium.com/@madishettimounika123/capture-lists-in-swift-19142660703e?source=rss-3535d6612cda------2</link>
            <guid isPermaLink="false">https://medium.com/p/19142660703e</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[capture-lists]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Schrodinger's Cat]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 15:44:56 GMT</pubDate>
            <atom:updated>2021-07-17T18:06:16.899Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of us working with Swift might already knew that closures are reference types. They have strong access to variables surrounding them. But, what role does these Capture Lists play to make closures more effective?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*5cMWc86aOT4eKqWua2S5hQ.jpeg" /></figure><p>A capture list is used to control how the surrounding data can be captured inside a closure. It holds the data that is present at the time of closure creation, not when the closure is called.</p><p>For each object defined inside a capture list, a constant gets initialized to the value of the object(var or constant) that has same name in the surrounding scope of the closure. So Change in value of the variable outside closure doesn’t effect the value inside( since, separate memory is created for the variable inside)</p><blockquote>Representation of a capture list-</blockquote><blockquote>[object1, object2, object3,…..]</blockquote><h4>First example:</h4><p>Without Capture List: Closure accessing variables x, y. Here the closure is capturing the values of variables at the time of calling it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1u7z46F29Yu0uCirKID85w.png" /><figcaption>fig.1.0. without a capture list</figcaption></figure><p>With Capture List: Closure accessing x, y. x denoted as a capture list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcJZKaA4EX77cMBzKNy7qg.png" /><figcaption>fig.1.1. With a capture list [x]</figcaption></figure><h4>Second Example:</h4><p>okay! So Now we know how capture lists work. but does this work same for reference types as well?</p><p>Let’s find out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFqYNNHrnqopi-AM2lYwOw.png" /><figcaption>fig.2.0. Without a capture list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIfcoejhcytEmkWqI4mgLQ.png" /><figcaption>fig.2.1. With a capture list [x]</figcaption></figure><p>Now the entry inside capture Lists behaving same as how a normal reference type works when we assign it to another variable. Yes! Pointing to the same memory location. Therefore, No changes observed while capturing reference types.</p><p>You can also define a capture list with weak or unowned to remove strong reference</p><blockquote>Representation:</blockquote><blockquote>[weak object1, unowned object 2,…]</blockquote><h4>Tip:</h4><p>Don’t forget to use “in” keyword after the capture list. It would not work otherwise #personal_experience 😺</p><p>Interesting writeups on their way to fillup your minds. Stay tuned!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19142660703e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>