<?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 Rohan Sanap on Medium]]></title>
        <description><![CDATA[Stories by Rohan Sanap on Medium]]></description>
        <link>https://medium.com/@therohansanap?source=rss-4fcb5fb102b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CCBfINwfkUYqgLas.</url>
            <title>Stories by Rohan Sanap on Medium</title>
            <link>https://medium.com/@therohansanap?source=rss-4fcb5fb102b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:18:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@therohansanap/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[Driver and Signal and Relays]]></title>
            <link>https://medium.com/@therohansanap/driver-and-signal-and-relays-942fd35070ea?source=rss-4fcb5fb102b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/942fd35070ea</guid>
            <category><![CDATA[rxcocoa]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[rxswift]]></category>
            <dc:creator><![CDATA[Rohan Sanap]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 10:39:11 GMT</pubDate>
            <atom:updated>2020-04-05T10:39:11.264Z</atom:updated>
            <content:encoded><![CDATA[<p>Make sure you have read and understood the use of share operator by reading <a href="https://link.medium.com/dWgnUEBXq5">its article</a> before reading this article.</p><p><strong>Driver</strong></p><p>This is the most elaborate trait. Its intention is to provide an intuitive way to write reactive code in the UI layer, or for any case where you want to model a stream of data Driving your application.</p><ul><li>Can’t error out.</li><li>Observe occurs on main scheduler.</li><li>Shares side effects (share(replay: 1, scope: .whileConnected)).</li></ul><p><strong>Why is it named Driver</strong></p><p>Its intended use case was to model sequences that drive your application. E.g.</p><ul><li>Drive UI from CoreData model.</li><li>Drive UI using values from other UI elements (bindings). …</li></ul><p>Like normal operating system drivers, in case a sequence errors out, your application will stop responding to user input.</p><p>It is also extremely important that those elements are observed on the main thread because UI elements and application logic are usually not thread safe.</p><p>Also, a Driver builds an observable sequence that shares side effects. E.g.</p><p><strong>Practical usage example</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cf7938bc6b36f3f7aeb36eadd41f659/href">https://medium.com/media/9cf7938bc6b36f3f7aeb36eadd41f659/href</a></iframe><p>The intended behavior of this code was to:</p><ul><li>Throttle user input.</li><li>Contact server and fetch a list of user results (once per query).</li><li>Bind the results to two UI elements: results table view and a label that displays the number of results.</li></ul><p>So, what are the problems with this code?</p><ul><li>If the fetchAutoCompleteItems observable sequence errors out (connection failed or parsing error), this error would unbind everything and the UI wouldn’t respond any more to new queries.</li><li>If fetchAutoCompleteItems returns results on some background thread, results would be bound to UI elements from a background thread which could cause non-deterministic crashes.</li><li>Results are bound to two UI elements, which means that for each user query, two HTTP requests would be made, one for each UI element, which is not the intended behavior.</li></ul><p>A more appropriate version of the code would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97135470f9e18edec51af9aaea58d75a/href">https://medium.com/media/97135470f9e18edec51af9aaea58d75a/href</a></iframe><p>Making sure all of these requirements are properly handled in large systems can be challenging, but there is a simpler way of using the compiler and traits to prove these requirements are met.</p><p>The following code looks almost the same:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee3cbd083d09334a3add5350397ca809/href">https://medium.com/media/ee3cbd083d09334a3add5350397ca809/href</a></iframe><p>So what is happening here?<br>This first asDriver method converts the ControlProperty trait to a Driver trait.</p><p>query.rx.text.asDriver()</p><p>Notice that there wasn’t anything special that needed to be done. Driver has all of the properties of the ControlProperty trait, plus some more. The underlying observable sequence is just wrapped as a Driver trait, and that’s it.</p><p>The second change is:</p><p>.asDriver(onErrorJustReturn: [])</p><p>Any observable sequence can be converted to Driver trait, as long as it satisfies 3 properties:</p><ul><li>Can’t error out.</li><li>Observe on main scheduler.</li><li>Sharing side effects (share(replay: 1, scope: .whileConnected)).</li></ul><p>So how do you make sure those properties are satisfied? Just use normal Rx operators. asDriver(onErrorJustReturn: []) is equivalent to following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a352a1c1967d93dcf0ab0f2b5a3dda/href">https://medium.com/media/32a352a1c1967d93dcf0ab0f2b5a3dda/href</a></iframe><p>The final piece is using drive instead of using bind(to:).</p><p>drive is defined only on the Driver trait. This means that if you see drive somewhere in code, that observable sequence can never error out</p><p>and it observes on the main thread, which is safe for binding to a UI element.</p><p>Note however that, theoretically, someone could still define a drive method to work on ObservableType or some other interface, so to be extra safe, creating a temporary definition with let results: Driver&lt;[Results]&gt; = …before binding to UI elements would be necessary for complete proof. However, we’ll leave it up to the reader to decide whether this is a realistic scenario or not.</p><h4><strong>Signal</strong></h4><p>A Signal is similar to Driver with one difference, it does <strong>not </strong>replay the latest event on subscription, but subscribers still share the sequence’s computational resources.</p><p>It can be considered a builder pattern to model Imperative Events in a Reactive way as part of your application.</p><p>A Signal:</p><ul><li>Can’t error out.</li><li>Delivers events on Main Scheduler.</li><li>Shares computational resources (share(scope: .whileConnected)).</li><li>Does NOT replay elements on subscription.</li></ul><h4><strong>Relays</strong></h4><p>There are two types of relays, viz., PublishRelay and BehaviourRelay. They behave exactly like their parallel Subjects with two important changes</p><ul><li>Relays never complete.</li><li>Relays never emit error.</li></ul><p>In essence, Relays only emit .next events and never terminate.</p><p>From a use case point of view, it is generally accepted understanding that</p><ul><li>BehaviourRelay represent state — It makes sense to replay its recent value hence BehaviourRelays have asDriver operator.</li><li>PublishRelay represent events — It makes no sense to replay an event hence PublishRelays do not replay the latest value.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=942fd35070ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction]]></title>
            <link>https://medium.com/swift-india/introduction-1bf0368dbd6?source=rss-4fcb5fb102b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bf0368dbd6</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Rohan Sanap]]></dc:creator>
            <pubDate>Thu, 10 Oct 2019 14:00:19 GMT</pubDate>
            <atom:updated>2019-10-10T14:12:51.064Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding `share` operator</h3><p>The chain of operators get re-executed with each new subscription. Consider the following code:</p><pre>let observable = Observable&lt;Int&gt;.create { observer -&gt; Disposable in<br>  // Simulating a very resource expensive operation<br>  print(&quot;Creating observable...&quot;)<br>  DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 10, execute: {<br>    observer.onNext(1)<br>    observer.onCompleted()<br>  })<br>  return Disposables.create()<br>}</pre><pre>let subscriptionA = observable.subscribe()<br>let subscriptionB = observable.subscribe()</pre><p>Output:</p><pre>Creating observable...<br>Creating observable...</pre><p>Here you see that Creating observable… is printed twice! That is because the code inside the observable creation closure is executed on every new subscription. In this example we performed it twice in the last two lines. This is where shareoperator comes into picture. <strong>This operator shares single subscription across all subscribers.</strong> Thus the observable won’t be recreated and the chain of operations (if any) won’t be re-executed.</p><pre>let sharedSubscription = observable.share()<br>let subscriptionA = sharedSubscription.subscribe()<br>let subscriptionB = sharedSubscription.subscribe()</pre><p>This is a very simple example. But, image if the code inside the closure was a network request. You would be performing the same network request twice. Consider following example:</p><pre>Class SomeViewModel {<br>  ...<br>  let result = userTappedButton.flatMapLatest { apiService.rx.getFriend() }<br>  let name = result.map { $0.name }<br>  let phone = result.map { $0.phone }<br>  ...<br>}</pre><p>You have a result stream which reacts to a user’s tap on a button, and fires a network request to some API service. You map these results into two separate streams of the friend’s name and phone number. Later on, in your view controller, you will subscribe to the name and phone streams and expect to get the latest friend’s name and phone when your user taps on the button.</p><pre>Class SomeViewController: UIViewController {<br>  ...<br>  //Bind your viewModel&#39;s outputs to your UI<br>  viewModel.name.bind(to: nameLabel.rx.text).disposed(by: bag)<br>  viewModel.phone.bind(to: phoneLabel.rx.phone).disposed(by: bag)<br>  ...<br>}</pre><p>In the following example, every time you subscribe to name and phone you will actually be getting an entirely different stream, meaning an entirely different network request per subscription!</p><p>share to the rescue! <strong>It lets you define streams that share resources among their subscribers.</strong> Meaning, each subscriber to the stream will get the exact same stream, and will not invoke additional computations or resources for that origin stream. In the example above, merely adding share operator after original flatMapLatest will solve the problem and only one network request will be done.</p><pre>Class SomeViewModel {<br>  ...<br>  let result = userTappedButton<br>                .flatMapLatest { apiService.rx.getFriend() }<br>                .share()<br>                <br>  let name = result.map { $0.name }<br>  let phone = result.map { $0.phone }<br>  ...<br>}</pre><h3>Going deeper</h3><p>share() is abstract form of function share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) with it’s default values. Let’s break these two parameters for better understanding.</p><h3>Replay</h3><p>This is pretty self explanatory. It is count of elements that we wish to replay to a new subscriber. In vague terms, with it’s default value as 0 it makes your stream act as a PublishSubject, meaning new subscriber only get’s future values but don’t know of anything that happened before the point of subscription.</p><p>In contrast, setting replay’s value to 1 makes your stream act like a BehaviourSubject and setting it’s value to any other bigger value makes your stream act as a ReplaySubject.</p><h3>Scope</h3><p>This argument has two possible values, viz., .whileConnected and .forever. In most of the cases you will use .whileConnected and it will be enough for you. In very rare cases you will have to use value .forever.</p><p>This argument has two possible values, viz., .whileConnected and .forever. In most of the cases you will use .whileConnected and it will be enough for you. In very rare cases you will have to use value .forever.</p><p>Here’s how each of these works:</p><ul><li>.whileConnected: Values are replayed (when replay is larger than 0) in a reference-counting manner, much like ARC. When the number of subscribers drops from 1 to 0, the internal “cache” of the shared stream is cleared. It’s safe to use operators like retry since these will get a fresh stream for each retry and have a cleared internal state.</li><li>.forever: The internal cache of the stream is <strong>not</strong> cleared, even after the number of subscribers drops from 1 to 0. Meaning, future subscribers could potentially get stale events from the internal cache of the shared stream. It’s not recommended using operators such as retry in this case, as the retry might “carry” stale events and cause unexpected behaviour.</li></ul><p>Consider the following example and you will get a proper idea about difference between two</p><h4>Example for .whileConnected</h4><pre>let observable = Observable&lt;Int&gt;<br>    .interval(.seconds(1), scheduler: MainScheduler.instance)<br>    .share(replay: 1, scope: .whileConnected)</pre><pre>var subscription1: Disposable = observable<br>    .debug(&quot;Sub 1&quot;)<br>    .subscribe()</pre><pre>DispatchQueue.main.asyncAfter(deadline: .now() + 3) {<br>    print(&quot;After t+3 seconds&quot;)<br>    subscription1.dispose()<br>}</pre><pre>var subscription2: Disposable?<br>DispatchQueue.main.asyncAfter(deadline: .now() + 10) {<br>    print(&quot;After t+10 seconds&quot;)<br>    subscription2 = observable<br>        .debug(&quot;Sub 2&quot;)<br>        .subscribe()<br>}</pre><p>Output -</p><pre>2019-07-18 16:10:42.994: Sub 1 -&gt; subscribed<br>2019-07-18 16:10:43.996: Sub 1 -&gt; Event next(0)<br>2019-07-18 16:10:44.996: Sub 1 -&gt; Event next(1)<br>2019-07-18 16:10:45.997: Sub 1 -&gt; Event next(2)<br>After t+3 seconds<br>2019-07-18 16:10:46.388: Sub 1 -&gt; isDisposed<br>After t+10 seconds<br>2019-07-18 16:10:53.096: Sub 2 -&gt; subscribed<br>2019-07-18 16:10:54.098: Sub 2 -&gt; Event next(0)<br>2019-07-18 16:10:55.097: Sub 2 -&gt; Event next(1)<br>After t+13 seconds<br>2019-07-18 16:10:56.097: Sub 2 -&gt; isDisposed</pre><p>After t+10, when subscription2 is subscribed, it restarts the sequence and no older value is replayed on it even when we have replay number set to 1. This is because before subscription2 is subscribed, we dispose subscription1 and the causes the observable to have 0 subscribers/subscriptions connect. This is when the cache is cleared and all older values are dump.</p><h4>Example for .forever</h4><p>In the above example code snippet, just change .whileConnected to .forever on line number 3 and you will get following output</p><pre>2019-07-18 16:11:51.165: Sub 1 -&gt; subscribed<br>2019-07-18 16:11:52.168: Sub 1 -&gt; Event next(0)<br>2019-07-18 16:11:53.168: Sub 1 -&gt; Event next(1)<br>2019-07-18 16:11:54.168: Sub 1 -&gt; Event next(2)<br>After t+3 seconds<br>2019-07-18 16:11:54.463: Sub 1 -&gt; isDisposed<br>After t+10 seconds<br>2019-07-18 16:12:01.170: Sub 2 -&gt; subscribed<br>2019-07-18 16:12:01.170: Sub 2 -&gt; Event next(2)<br>2019-07-18 16:12:02.171: Sub 2 -&gt; Event next(0)<br>2019-07-18 16:12:03.171: Sub 2 -&gt; Event next(1)<br>After t+13 seconds<br>2019-07-18 16:12:04.170: Sub 2 -&gt; isDisposed</pre><p>If we observe the difference between this output and the previous output, we see that after subscription of subscription2, value 2 is replayed on it from the previous stream as the cache is not cleared because the scope is .forever.</p><h3>References</h3><p>For a more holistic and deeper understanding of Connectable Observable Sequences in RxSwift with operators such as publish, replay, and refCount, please refer to these articles and playground:</p><ul><li><a href="https://arctouch.com/blog/rxswift-connectable-observable-sequences/">https://arctouch.com/blog/rxswift-connectable-observable-sequences/</a></li><li><a href="https://arctouch.com/blog/rxswift-share-operator/">https://arctouch.com/blog/rxswift-share-operator/</a></li><li><a href="https://github.com/ReactiveX/RxSwift/blob/master/Rx.playground/Pages/Connectable_Operators.xcplaygroundpage/Contents.swift">https://github.com/ReactiveX/RxSwift/blob/master/Rx.playground/Pages/Connectable_Operators.xcplaygroundpage/Contents.swift</a></li><li><a href="https://medium.com/gett-engineering/rxswift-share-ing-is-caring-341557714a2d">https://medium.com/gett-engineering/rxswift-share-ing-is-caring-341557714a2d</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bf0368dbd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-india/introduction-1bf0368dbd6">Introduction</a> was originally published in <a href="https://medium.com/swift-india">Swift India</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>