<?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 Maor Korakin on Medium]]></title>
        <description><![CDATA[Stories by Maor Korakin on Medium]]></description>
        <link>https://medium.com/@maorkorakin?source=rss-9b8e2e297785------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PCxw0fXBcNKe6Pen.</url>
            <title>Stories by Maor Korakin on Medium</title>
            <link>https://medium.com/@maorkorakin?source=rss-9b8e2e297785------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:53:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maorkorakin/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[Using RxJava autoConnect() and Relay to host a stream in a ViewModel]]></title>
            <link>https://tech.instacart.com/view-model-state-preservation-using-autoconnect-d75ee791954b?source=rss-9b8e2e297785------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75ee791954b</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[viewmodel]]></category>
            <dc:creator><![CDATA[Maor Korakin]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 02:45:36 GMT</pubDate>
            <atom:updated>2020-01-24T06:17:47.529Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>To preserve and share the state of a stream (e.g. for rotations, dialogs), we can host the stream in Android’s <em>ViewModel</em> by using <a href="https://medium.com/@maorkorakin/rx-publish-examples-58ae196908f0"><em>.replay(1).autoConnect()</em></a> to share the stream’s state and a <a href="https://github.com/JakeWharton/RxRelay"><em>Relay</em></a> to share the input.</p><p>For example:</p><pre>class MyViewModel : ViewModel() {</pre><pre>val inputStream = PublishRelay.create&lt;Input&gt;()</pre><pre>val viewsState: Observable&lt;ViewState&gt; <strong>= <br></strong>        <strong>inputStream</strong> <br>            // Transformed to a stream of view states<br><strong>            .<em>toViewState</em>() </strong><br>            // Shared between subscribers<br>            <strong>.replay(1).autoConnect(1)</strong> { disposables.add(it) }<br>}</pre><p>Full example <a href="https://gist.github.com/mkorakin/557dea509f757a3f3f9c5fcc8f720e78">here</a>.</p><h3>Sharing the state</h3><p>When disposing a connection to an Observable that is a not a <a href="https://medium.com/@maorkorakin/rx-publish-examples-58ae196908f0">ConnectableObservable</a>, the entire stream is disposed.</p><p>For example, when subscribing to a network request in an Activity, we lose the state on rotation (or any other configuration change):</p><pre>endpoint<br>    .getData()<br>    .subscribe {                   // Create a connection<br>        titleView.text = ...       // Present the data<br>    }        <br>    .<em>let </em>{ disposables.add(it) }   // To be disposed in onDestroy()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2JHKI-AIuzILcP0zK-xfA.png" /><figcaption>Disposing an unpublished stream</figcaption></figure><p>We may restore the view state in some way (e.g. with <em>savedInstanceState</em>), but then on rotations we would create another network request (and cancel any network request if active).</p><p>Hosting the stream in a <em>lifecycle.ViewModel</em>, we can have a stream lifecycle decoupled from the Activity’s. Using <em>.autoConnect()</em> we define the Observable to connect upstream (to the endpoint in this example) when the first Activity subscribes. When the activity disposes the connection, the upstream is kept alive. When the ViewModel itself is disposed (in onCleared) we dispose the upstream:</p><pre>class MyViewModel(<br>    val endpoint: Endpoint<br>) <strong>: </strong>ViewModel() {</pre><pre>    private val disposables = CompositeDisposable()</pre><pre>    val viewState: Observable&lt;Data&gt; =<br>        endpoint<br>            .getData()</pre><pre><strong>            // Replay the last emitted value to new subscribers.</strong><br>            <strong>.replay(1)</strong></pre><pre><strong>            // A single upstream connection is made on <br>            // the first subscription and shared with <br>            // all future subscribers.<br>            .autoConnect(1)</strong> { <br>                <strong>// Upstream disposable kept for later disposal.</strong><br>                disposables.add(it) <br>            }</pre><pre><strong>    </strong>override fun onCleared() {<br>        disposables.dispose()<br>        super.onCleared()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*in6ISia5PArSEYGBanIVgA.png" /><figcaption>A published stream kept alive on rotations.</figcaption></figure><h3>Sharing the input</h3><p>To have user input as the origin of the stream hosted in a ViewModel, we can use a Relay.<br>To extend the example above, on user requests to refresh we create new network requests:</p><pre>val <strong>inputStream</strong> <strong>=</strong> <strong>PublishRelay</strong>.create&lt;Input&gt;()</pre><pre>val viewsState: Observable&lt;Data&gt; =<br>    <strong>inputStream<br></strong>        switchMap {<strong><br>            </strong>endpoint.getData()<br>        }<br>        <strong>.replay(1).autoConnect(1)</strong> { disposables.add(it) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QVZ2LV6SqV8iiriqoda8sA.png" /><figcaption>Hosting a stream in a ViewModel using <em>Relay</em> and <em>.autoConnect()</em></figcaption></figure><h3>Examples of stream states</h3><p>Most RxJava operators have some state that we may want to preserve. Some examples:</p><h4>.scan() stores its last output:</h4><pre>clicks<br>    .scan(0) { state, _ -&gt; state + 1 } // Count clicks<br>    .subscribe { … }</pre><h4>.combineLatest() stores its last inputs:</h4><pre>Observable<br>    .combineLatest(dataStream, filterStream) { data, filter -&gt;<br>        data.filter(filter)<br>    }</pre><h4>.switchMap() maintains the active downstream connection:</h4><pre>onOffToggle<br>    .switchMap {<br>        // Toggle a connection to a data source<br>        when (it) {<br>            true -&gt; source.data()<br>            false -&gt; Observable.empty()<br>        }<br>    }</pre><h3>Summary</h3><p>Generally speaking, <em>.autoConnect()</em> (and <a href="https://medium.com/@maorkorakin/rx-publish-examples-58ae196908f0">its fellow operators</a>) allow us to host a stream and maintain its state in a separate lifecycle from its subscribers.</p><p>Tying a stream’s lifecycle to a ViewModel’s, we can share its state across rotations. The state and input can also be shared with other views — for example between a dialog and an Activity, or between Fragments in a master-detail design.<br>We can also choose to host streams in other lifecycles, for example for implementing a global in-memory cache, or to have a lifecycle tied to a specific module.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75ee791954b" width="1" height="1" alt=""><hr><p><a href="https://tech.instacart.com/view-model-state-preservation-using-autoconnect-d75ee791954b">Using RxJava autoConnect() and Relay to host a stream in a ViewModel</a> was originally published in <a href="https://tech.instacart.com/">tech-at-instacart</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RX publish() examples]]></title>
            <link>https://tech.instacart.com/rx-publish-examples-58ae196908f0?source=rss-9b8e2e297785------2</link>
            <guid isPermaLink="false">https://medium.com/p/58ae196908f0</guid>
            <category><![CDATA[connectableobservable]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[xr]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Maor Korakin]]></dc:creator>
            <pubDate>Thu, 07 Mar 2019 06:51:46 GMT</pubDate>
            <atom:updated>2020-01-24T06:23:28.343Z</atom:updated>
            <content:encoded><![CDATA[<h4>Probably the easiest way to understand RX’s <a href="http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html">ConnectableObservable</a> is with examples — here are some.</h4><p>To share a stream among subscribers we use <a href="http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html">ConnectableObservable</a>. <br>We have then to specify:<br>1. Should we replay the last events to new subscribers (<em>.publish() / .replay()</em>)<br>2. When to connect upstream (<em>.refCount() / .connect() / .autoConnect()</em>)</p><p>Below are logs of multiple consumers connecting to Observable.interval() in different ways.</p><h4>Not connectable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*pdnPKZXvg4hIwkKF7eoxTw.png" /><figcaption>Not Connectable</figcaption></figure><pre>val stream = Observable.interval(1, TimeUnit.SECONDS)</pre><pre>stream<br>    .subscribe { Timber.i(&quot;<strong>Subscription A</strong>: $it&quot;) <br><br>stream<br>    .delaySubscription(4, TimeUnit.SECONDS)<br>    .subscribe { Timber.e(&quot;<strong>Subscription B</strong>: $it&quot;) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*0IkdLhZpGFgHMV8NYDDgJw.png" /></figure><h3>Replaying to new subscribers</h3><h4>.publish()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*oXbVr8V-SaBiA0KCjuZBYQ.png" /><figcaption>.publish()</figcaption></figure><pre>val stream = Observable<br>    .interval(0, 2, TimeUnit.SECONDS)<br>    <strong>.publish()</strong>.refCount()</pre><pre>stream<br>    .doOnSubscribe { Timber.i(&quot;A subscribed.&quot;) }<br>    .subscribe { Timber.i(&quot;Subscription A: $it&quot;) }</pre><pre>stream<br>    .delaySubscription(1, TimeUnit.SECONDS)<br>    .doOnSubscribe { Timber.e(&quot;B subscribed.&quot;) }<br>    .subscribe { Timber.e(&quot;Subscription B: $it&quot;) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*ZN1PBJqrKSkS_-wB-y2FCA.png" /></figure><h4>.replay()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*v7T074tOeOfIs-TPYB4vzA.png" /><figcaption>.replay()</figcaption></figure><pre>val stream = Observable<br>    .interval(0, 2, TimeUnit.SECONDS)<br>    <strong>.replay(1)</strong>.refCount()</pre><pre>stream<br>    .doOnSubscribe { Timber.i(&quot;A subscribed.&quot;) }<br>    .subscribe { Timber.i(&quot;Subscription A: $it&quot;) }</pre><pre>stream<br>    .delaySubscription(1, TimeUnit.SECONDS)<br>    .doOnSubscribe { Timber.e(&quot;B subscribed.&quot;) }<br>    .subscribe { Timber.e(&quot;Subscription B: $it&quot;) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*uEHFgYjLvtd4Jg00nZd9Fg.png" /></figure><h3>Connecting upstream</h3><h4>.refCount<strong>()</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fMS18luv1teuZEvSOVy4Q.png" /><figcaption>refCount()</figcaption></figure><pre>val stream = Observable<br>    .interval(1, TimeUnit.SECONDS)<br><strong>    .publish().refCount()</strong></pre><pre>stream<br>    .take(5)<br>    .doOnTerminate { Timber.i(&quot;A disposed.&quot;) }<br>    .subscribe { Timber.i(&quot;Subscription A: $it&quot;) }<br><br>stream<br>    .delaySubscription(2, TimeUnit.SECONDS)<br>    .take(2)<br>    .doOnTerminate { Timber.e(&quot;B disposed.&quot;) }<br>    .subscribe { Timber.e(&quot;Subscription B: $it&quot;) }<br><br>stream<br>    .delaySubscription(10, TimeUnit.SECONDS)<br>    .take(2)<br>    .doOnTerminate { Timber.e(&quot;C disposed.&quot;) }<br>    .subscribe { Timber.e(&quot;Subscription C: $it&quot;) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*JFEmJ3DtnQExN7jYjnlLtQ.png" /></figure><h4>.autoConnect()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hq06nXcbD6WPZscaSzLPw.png" /><figcaption>autoConnect()</figcaption></figure><pre>val stream = Observable<br>    .interval(1, TimeUnit.SECONDS)<br>    <strong>.publish().autoConnect(1) { disposables.add(it) }</strong><br><br>stream<br>    .take(5)<br>    .doOnTerminate { Timber.i(&quot;A disposed.&quot;) }<br>    .subscribe { Timber.i(&quot;Subscription A: $it&quot;) }<br><br>stream<br>    .delaySubscription(2, TimeUnit.SECONDS)<br>    .take(2)<br>    .doOnTerminate { Timber.e(&quot;B disposed.&quot;) }<br>    .subscribe { Timber.e(&quot;Subscription B: $it&quot;) }<br><br>stream<br>    .delaySubscription(10, TimeUnit.SECONDS)<br>    .take(2)<br>    .doOnTerminate { Timber.e(&quot;C disposed.&quot;) }<br>    .subscribe { Timber.e(&quot;Subscription C: $it&quot;) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*A3XtQTrf6kBYNePYb_mE9w.png" /></figure><h3>.publish { … }</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrDOoz0zYu1rDxUQ7gJ7WA.png" /><figcaption>.publish { … }</figcaption></figure><pre>Observable<br>    .interval(0, 1, TimeUnit.SECONDS)<br>    <strong>.publish { </strong>published -&gt;<br>        Observable.merge(<br>            published.map { &quot;Stream A: $it&quot; },<br>            published.map { &quot;Stream B: $it&quot; }<br>        )<br>    <strong>}</strong><br>    .subscribe { Timber.i(it) }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/86/1*Tcr4RrFqVd9wdafg3hRBZg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58ae196908f0" width="1" height="1" alt=""><hr><p><a href="https://tech.instacart.com/rx-publish-examples-58ae196908f0">RX publish() examples</a> was originally published in <a href="https://tech.instacart.com/">tech-at-instacart</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>