<?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[Crunching RxAndroid - Medium]]></title>
        <description><![CDATA[A step-by-step tutorial about Reactive Programming on Android - Medium]]></description>
        <link>https://medium.com/crunching-rxandroid?source=rss----a5b52759c69b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Crunching RxAndroid - Medium</title>
            <link>https://medium.com/crunching-rxandroid?source=rss----a5b52759c69b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:37:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/crunching-rxandroid" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 10]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-10-cc0c33108ee2?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/cc0c33108ee2</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[gde]]></category>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Fri, 23 Sep 2016 15:25:57 GMT</pubDate>
            <atom:updated>2016-09-23T21:29:51.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><p><em>In the </em><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-9-37cfc28e2249#.nejceclwl"><em>latest episode of this series</em></a><em>, we talked about how an Observable can be retained through the lifecycle of the Activity, but we still lack a very important piece that will make Reactive Programming even more valuable in our every day life.</em></p><h4>A step back</h4><p>We shall all be pretty familiar with the way Android is heavily based upon a <strong>listener pattern </strong>derived from the <a href="https://en.wikipedia.org/wiki/Observer_pattern">Observer one</a>, and we are pretty sure that most of the times there’s a <em>*Listener</em> that will be notified whenever something changes. But we don’t really have to deal with that and we can actually use the power of RxJava to <strong>convert every listener into something emitting information that we can subscribe to</strong>.</p><p>First of all, let’s see how we could wrap a very long operation (such as a File download) into a more Reactive approach. Let’s suppose we have something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7029e92cafe69aaa29f1eb6d74b13d22/href">https://medium.com/media/7029e92cafe69aaa29f1eb6d74b13d22/href</a></iframe><p>Now, we can make use of the <em>Observable.fromCallable() </em>factory method, so that we create (out of our method) a new Observable that will not only give us a Reactive approach, but also <strong>redirect our Exception to the onError method of our chain</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f186309bcc9b51dfa83edac84fec87ed/href">https://medium.com/media/f186309bcc9b51dfa83edac84fec87ed/href</a></iframe><p>Of course, with the magic of lambdas this would be downsized to just a single line, but we get the idea.</p><h4>Reacting to callbacks</h4><p>Luckily, RxJava doesn’t come with just a wrapper for synchronous functions, but it also allows us to wrap asynchronous callbacks by making use of the factory method <em>Observable.fromAsync()</em>. Let’s see how it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79589122d82c89921977a6530509d02f/href">https://medium.com/media/79589122d82c89921977a6530509d02f/href</a></iframe><p>As we can see, this method takes two parameters, the first one being an <em>Action1</em>, while <strong>the second one defines the kind of Backpressure</strong> wanted for the Observable, picking from a wide variety of types defined by the <a href="http://reactivex.io/RxJava/javadoc/rx/AsyncEmitter.BackpressureMode.html">BackpressureMode</a> enum (we will cover it in a following episode).</p><p>Studying more carefully <em>Action1&lt;&gt;</em>, we see that its generic type resolves to <a href="http://reactivex.io/RxJava/javadoc/rx/AsyncEmitter.html">AsyncEmitter&lt;T&gt;</a>, where the <em>T</em> is the type of data we will be emitting. Inside this <em>Action1</em>, we can create our listener, so that we can react properly to the events.</p><p>Let’s see an example made upon the Firebase Database api, which returns us a DataSnapshot when a ValueEventListener is registered:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01d1c0f185572c2104485e7b7fb444d1/href">https://medium.com/media/01d1c0f185572c2104485e7b7fb444d1/href</a></iframe><p>Apart from the implementation of the ValueEventListener interface, we can see that we inject an <em>AsyncEmitter&lt;DataSnapshot&gt;</em> in the constructor, then we emit the data as soon as it changes by using the <em>onNext()</em> method in the emitter (we complete right away as we just want one value) and we instead propagate the error in case of cancelation.</p><p>At this point, we just need to wire things up, and this is done pretty easily:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/023f886616af99209f806d4955ca3300/href">https://medium.com/media/023f886616af99209f806d4955ca3300/href</a></iframe><p>What’s important here is that when we use the <em>AsyncEmitter&lt;&gt;</em> we get in the <em>Action1</em> to create a listener that we attach to the database, so that we can then deal with the stream of data returned from the database.</p><blockquote><strong>Note</strong>: starting from <a href="https://github.com/ReactiveX/RxJava/issues/4455">RxJava 1.1.10</a>, the <strong>Observable.fromAsync()</strong> factory method has been renamed <strong>Observable.fromEmitter()</strong>, as <a href="https://medium.com/@pieper">Plastix</a> mentioned in the comments.</blockquote><h4>Conclusion</h4><p>Of course, we could have done it with the <em>Observable.create()</em> factory method that would work in a very similar way, but the very reason why these two methods have been created is that <em>create()</em> doesn’t give us any weapon for dealing with <strong>Backpressure</strong> and this is why we shall always pick those upon the latter (if you want to know more about it, check out the amazing speech made from my friend <a href="https://twitter.com/sasa_sekulic">Sasa Sekulic</a>, together with the <a href="https://speakerdeck.com/mrsasha/recipes-in-rxjava-for-android">related slides</a>).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJrWTMqd_UUo%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJrWTMqd_UUo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJrWTMqd_UUo%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/54f8a42545467cb5a84f08f9adee90c9/href">https://medium.com/media/54f8a42545467cb5a84f08f9adee90c9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc0c33108ee2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-10-cc0c33108ee2">Crunching RxAndroid — Part 10</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 9]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-9-37cfc28e2249?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/37cfc28e2249</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[rxandroid]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Tue, 31 May 2016 10:01:17 GMT</pubDate>
            <atom:updated>2016-05-31T10:01:16.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><p><em>In the last episode of this series, we studied subjects and how they could be helpful while managing the configuration changes of the Activity, together with a retained Fragment. In this article, we are instead exploring another way to retain the running Observable, thanks to the </em><a href="https://gist.github.com/Takhion/8b7514bdc7b82e914ea7a866871654b2"><em>idea and help</em></a><em> of my friend and fellow Android Developer </em><a href="https://twitter.com/workingkills"><em>Eugenio Marletti</em></a><em>.</em></p><h4>Hooking in the Activity lifecycle</h4><p>We are all aware of the <a href="https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState</a>/<a href="https://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)">onRestoreInstanceState</a> pair, but what if we do not have a <a href="https://developer.android.com/reference/android/os/Parcelable.html">Parcelable</a> or <a href="https://developer.android.com/reference/java/io/Serializable.html">Serializable</a> object such as the <a href="http://reactivex.io/RxJava/javadoc/rx/Subscription.html">Subscription</a> one? Well, a few year ago, <em>before Fragments were a thing</em>, we could have used <a href="https://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onRetainNonConfigurationInstance()">onRetainNonConfigurationInstance</a> to save the Observable, but that procedure was deprecated in favour of the <a href="https://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)">setRetainInstance</a> method in the <a href="https://developer.android.com/reference/android/app/Fragment.html">Fragment API</a>. <a href="https://twitter.com/adamwp/status/720682392990535680">Even if it was safe to use</a> (and ironically, exactly what the support Fragments use to restore state), recently Google released a new pair in the <a href="https://developer.android.com/reference/android/support/v4/app/FragmentActivity.html">FragmentActivity</a> class (upon which the AppCompatActivity inherits) that will allow us to retain a custom state and retrieve it later: let’s welcome the <a href="https://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onRetainCustomNonConfigurationInstance()">onRetainCustomNonConfigurationInstance</a>/<a href="https://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#getLastCustomNonConfigurationInstance()">getLastCustomNonConfigurationInstance</a> team!</p><p>With the first method, we are able to save the current custom state and we are going to retrieve it later with the second one, making the state itself able to survive the configuration changes, thus being retained properly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f4e12a266da59154684805dfa8a3f30/href">https://medium.com/media/5f4e12a266da59154684805dfa8a3f30/href</a></iframe><p>What we did here was to return the current instance of the Observable (line 6), then we just cast it properly when we need it back (line 11). It’s pretty easy, isn’t it?</p><h4>Creating the right Observable</h4><p>Now, for the sake of the example, we need a long running Observable, such as this one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62f1dbb54919fc3e87a9d4cd828d1ef/href">https://medium.com/media/e62f1dbb54919fc3e87a9d4cd828d1ef/href</a></iframe><p>What we need then is to transform the Observable, if necessary, so that it can be observed more than once, surviving the unsubscription and the following resubscription on configuration change. For doing so, we are going to use the <a href="http://reactivex.io/RxJava/javadoc/rx/Observable.html#replay(int)">replay</a> operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EXRtpBVHhVGmSuUE01FCw.png" /></figure><p>The main difference is that this will make our Observable a Connectable one.</p><p>Being a <a href="http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html">Connectable Observable</a> means that it does not start emitting items when it’s subscribed to, but it needs the <em>connect()</em> method to be invoked.</p><p>We also specify a buffer size of 1, so that will replay only the last emitted item, thus avoiding wasting memory on older unneeded results.</p><p>Since we don’t really need to work with a ConnectableObservable this time, we will use the <a href="http://reactivex.io/RxJava/javadoc/rx/observables/ConnectableObservable.html#autoConnect%28%29">autoconnect()</a> method, making the connect() call happen automatically the first time we subscribe, and maintaining the connection to the source Observable even if we unsubscribe after.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feb61946c528f55d19088ae5d698579b/href">https://medium.com/media/feb61946c528f55d19088ae5d698579b/href</a></iframe><p>At this point, we can write a method that will return the proper observable, so that if we already have an instance, it will return it, otherwise it will invoke the method we just described and return us a new one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db66484a4adc7cbce28292a3e4174e23/href">https://medium.com/media/db66484a4adc7cbce28292a3e4174e23/href</a></iframe><h4>Writing the utility methods</h4><p>Now, we need to wire everything together, so that we can manage the subscription and unsubscription process at a higher level. We will do so by writing down 3 helper methods that will manage the subscription, the unsubscription and the “reset” of the Observable (making the Activity ready for a new iteration).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ba9c5f197b01becc28cc0c52d406e7c/href">https://medium.com/media/4ba9c5f197b01becc28cc0c52d406e7c/href</a></iframe><h4>Wiring up with the lifecycle</h4><p>Now, we need to make our code work with the Observable, so we need to create it in the onCreate method of the Activity and we subscribe to it right away, while we unsubscribe from it during the onDestroy phase of the Activity (we never know if the Observable completed or not, right?):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be53ab54233cbc323f6ba05270b40bb9/href">https://medium.com/media/be53ab54233cbc323f6ba05270b40bb9/href</a></iframe><p>Another option would be to make the subscribe and unsubscribe call in the onStart/onStop pair, where you would probably want to do it most of the time. You should instead avoid doing the process during in the onResume/onPause pair, as the Observable would disconnect and reconnect very often, for instance when a popup shows up or during a window focus switch in multiwindow mode.</p><p><em>It is worth mentioning that no fragments were harmed while restoring the Observables.</em></p><p><em>As usual, you can find the </em><a href="https://github.com/tiwiz/RxAndroidCrunch/releases/tag/Part9"><em>code related to this article</em></a><em> on GitHub and remember to share and star if you liked the post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37cfc28e2249" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-9-37cfc28e2249">Crunching RxAndroid — Part 9</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 8]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-8-bf1808c08f95?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/bf1808c08f95</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[xr]]></category>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Tue, 05 Apr 2016 10:31:02 GMT</pubDate>
            <atom:updated>2016-04-05T10:31:01.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><p><em>In the previous part of this series, we dissected a little bit of the core RxJava framework, with the idea of learning the most we could about the mechanics of the reactive programming on Android and </em><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-7-22be9e95650c#.8ef4cuv3v"><em>how to create and use custom operators</em></a><em>. This time, we will start talking about a very important — yet very hard to catch — element of the famous library, trying to understand where we can use this new component and where we do not need it.</em></p><h4>Subjects</h4><p>We already saw a lot of times that a Subscriber can listen to an Observable in order to receive the items emitted by the latter and, as far as we know, an Observable is an Observable and a Subscriber is a Subscriber. But… what if we have something that can be <em>both</em>? That something is a <strong>Subject</strong>, and we can see it as <em>a pipe that subscribes to an Observable and to which a Subscriber can subscribe to</em>. Moreover, a Subject can be used as a “dynamic” source of events, instead of using <strong>Observable.create()</strong> and similar, which is a synchronous operation. What’s the deal with that object, though? Let’s imagine a real life scenario where we have an <strong>Observable representing the status of a very long operation lasting several seconds, with a result that we want to display in the UI.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*P58riZK5Ehqi9mEbdWkmZg.gif" /><figcaption>Here’s a pic of the user having fun destroying the beloved subscription</figcaption></figure><p>We could create our Observable in the onCreate method of the Activity and subscribe to it immediately, at that point the user might rotate the device, triggering a configuration change: we would lose our subscription (even worse, we would risk leaking memory, if we do not unsubscribe from it) and, with it, all the work we already did before the user came in like a wrecking ball (<em>pun intended</em>).</p><p>What could we do, to avoid that? One solution would be to use a Subject to subscribe to our Observable in our onCreate method, store the Subject safely so that it can survive to a rotation and then subscribe to it in the onResume method with our proper subscriber, so that we get back the results.</p><p>To do so, we could do something like this: as an example, we can create a <em>headless Fragment</em> (but we could have done it with any POJO stored in a static field or outside the Activity, just to keep it as simple as possible for the demonstration) that will contain our Observable and in its onCreate method, we do what we need to do, such as emitting items every second. We then subscribe to it using a <strong>Subject</strong> and then, in the onResume method of the same Fragment, we give back the Subject to the Activity as if it was an Observable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93186314aa1e09b4f7996dc4705a271/href">https://medium.com/media/e93186314aa1e09b4f7996dc4705a271/href</a></iframe><p>In this way, every time our Activity is restored, <strong>we don’t lose any of the work we previously did</strong> but we have to remember that we have to unsubscribe from the Subject, otherwise we leak precious resources. <em>And we don’t want to do that, do we?</em></p><p>From a general point of view, we could be done with the main idea behind Subjects and that would be great… if only there weren’t <strong>four</strong> kinds! Don’t you worry, though, because they share the same properties and they differ mainly in the way they emit the items received.</p><h4>AsyncSubject</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DQkatSIqn8TCe6YcPIkPA.png" /></figure><p>The first type of Subject we are going to explore is the <a href="http://reactivex.io/RxJava/javadoc/rx/subjects/AsyncSubject.html">AsyncSubject</a>: <strong>it emits the last value (and only the last value) emitted by the source Observable, and only after that source Observable completes.</strong> Plus, if the source Observable does not emit any values, the AsyncSubject also completes without emitting any values. That means that no matter how many items we are trying and emitting, the Subject will receive them all, but <strong>it will only emit the last one</strong> and only after it receives the onCompleted event from the Observable it’s subscribed to. We usually use this particular kind of Subject whenever we don’t care about the intermediate results, but we just want the final computation result when the full chain is over. That is usually when the source Observable calls its onCompleted method, that will trigger the AsyncSubject emission.</p><h4>ReplaySubject</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-X_ANaiUONpeO5b6N1vOw.png" /></figure><p>The <a href="http://reactivex.io/RxJava/javadoc/rx/subjects/ReplaySubject.html">ReplaySubject</a> is by far the easiest of the group as <strong>it emits to any observer all of the items that were emitted by the source Observable</strong>, regardless of when the observer subscribes. That means that no matter when you subscribe, you will receive all the items previously emitted, so that you always have the full chain of events without the need to worry about timing issues or losing any data.</p><h4>PublishSubject</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-rm0ipPkaQ7ypojLfNdiA.png" /></figure><p>This <a href="http://reactivex.io/RxJava/javadoc/rx/subjects/PublishSubject.html">kind of Subject</a> is very similar to the BehaviorSubject, except from the fact that <strong>the final Subscriber will receive only the items that are emitted after the subscription takes place</strong>. Let’s understand it better by taking a look to the previous example, replacing the BehaviorSubject <strong>bs</strong> with new PublishSubject <strong>ps</strong>.</p><pre>source.subscribe(bs);<br>source emits 1<br>source emits 2<br>bs.subscribe(s1)<br>source emits 3 -&gt; s1 starts receiving items, starting from 3<br>source emits 4<br>source emits 5<br>bs.subscribe(s2)<br>source emits 6 -&gt; s2 starts receiving items, starting from 5<br>bs.subscribe(s3)<br>source emits onComplete -&gt; s3 receives the onComplete without receiving anything, s1, s2 receives onComplete</pre><p>As we can see from the <em>gist</em>, the PublishSubject behaves similarly to the BehaviorSubject except for the initial value: with the latter, you will receive the last item emitted before your Subscriber subscribed to the Subject, making that kind of object a very ductile companion for most of your background work, while the PublishSubject cannot guarantee that you won’t lose something if, for instance, an item is emitted while the device was rotating.</p><h4>BehaviorSubject</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJPHZt3t5PkCgcCiY8Zk8A.png" /></figure><p>Using the <a href="http://reactivex.io/RxJava/javadoc/rx/subjects/BehaviorSubject.html">BehaviorSubject</a>, each <strong>Subscriber will receive the items starting from the one most recently emitted by the source Observable</strong> (or an optional seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s). Let’s give an example in order to clarify the mechanics of this Subject with an Observable that emits a number every second (like the <strong>source</strong> one we saw at the beginning of the article), <strong>bs</strong> is a BehaviorSubject that subscribes to source and let <strong>s1</strong>, <strong>s2</strong> and <strong>s3</strong> be Subscribers that will subscribe to <strong>bs</strong> in different instants in the timeline.</p><pre>source.subscribe(bs);<br>source emits 1<br>source emits 2<br>bs.subscribe(s1) -&gt; s1 starts receiving items, starting from 2<br>source emits 3<br>source emits 4<br>source emits 5<br>bs.subscribe(s2) -&gt; s2 starts receiving items, starting from 5<br>source emits 6<br>bs.subscribe(s3) -&gt; s3 starts receiving items, starting from 6</pre><p>As we can see, when a Subscriber subscribes to the BehaviorSubject, it will receive the items starting from the last one emitted before it subscribed.</p><h4>Conclusion</h4><p>Subjects are a very important part of the framework and they are very versatile and useful in a pletora of situations, but they have a catch: once they call their onComplete or onError methods, they lose the possibility of moving data and <em>this is usually not the desired behavior</em>.<br>As usual, all the source and the examples for this article are available on the <a href="https://github.com/tiwiz/RxAndroidCrunch/releases/tag/Part8-Code">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf1808c08f95" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-8-bf1808c08f95">Crunching RxAndroid — Part 8</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 7]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-7-22be9e95650c?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/22be9e95650c</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[rxandroid]]></category>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Mon, 29 Feb 2016 13:56:01 GMT</pubDate>
            <atom:updated>2016-02-29T13:56:00.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><p><em>In the </em><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-6-6149764b59e#.pya5gtdqv"><em>last episode</em></a><em> of Cruching RxAndroid, we focused on understanding and implementing RxBinding in order to capture events from the Views we have in our layouts and, </em><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-5-1dd5fba89058#.dphi4ts8t"><em>previously</em></a><em>, we had the pleasure of diving into RxLifecycle, meeting for the first time the </em><strong><em>compose()</em></strong><em> operator, that will be one of the main focuses of this part.</em></p><h4>Are there custom operators in RxJava?</h4><p>OK, we have already seen the potential of standard operators. What if we actually wanted to create something custom? Furthermore, we do have two distinct families of operators: the first one is the group of operators that will affect in some ways the sequence of items emitted by the source Observable. We call these <em>Sequence Operators</em> and we use them through the <strong>lift()</strong> function. The second family, instead, is the one that we already saw in RxLifecycle and it encapsulates all those objects which duty is to change the Observable itself.<br>We call this last family <em>Transformational Operators</em> and we use them through the <strong>compose()</strong> method.</p><h4>Do we really need to use them?</h4><p>Usually, you would not really need to create your own operators as those provided with the framework are more than enough and creating custom operators is actually pretty risky, as <a href="https://plus.google.com/113316559156085910174">Dávid Karnok</a> can explain us in his 3 articles (<a href="http://akarnokd.blogspot.de/2015/05/pitfalls-of-operator-implementations.html">part 1</a>, <a href="http://akarnokd.blogspot.de/2015/05/pitfalls-of-operator-implementations_14.html">part 2</a> and <a href="http://akarnokd.blogspot.de/2015/05/pitfalls-of-operator-implementations_27.html">part 3</a>) but it would be nice to understand how things work and here we are!</p><h4>Sequence Operators</h4><p>If we take a look on how the Operator interface is defined, we can see that<br>it relies on a function that takes a <strong>Subscriber&lt;T&gt;</strong> and returns a <strong>Subscriber&lt;R&gt;</strong>: that means that we can change the type of the items emitted pretty easily but there is a catch: by creating our <strong>custom Operators</strong>, we risk breaking the chain of subscription and back pressure.</p><p>As aforementioned, these operators are those we use in order to affect the items emitted by the <strong>Observable</strong>: imagine that we want to create an operator that emits, per each item it receives, its square root.</p><p>The first thing we do is extend the <a href="http://reactivex.io/RxJava/javadoc/rx/Observable.Operator.html">Observable.Operator</a> class and then return a new Subscriber in the <strong>call()</strong> method of our operator.</p><p>We might also want to check if the subscriber is still available, so we can do it before forwarding the events of our operator to the <strong>Subscriber</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e0fe26e7df1141a330466485e23fa8c/href">https://medium.com/media/4e0fe26e7df1141a330466485e23fa8c/href</a></iframe><h4>Transformational Operators</h4><p>These operators are less risky then the Sequence ones, as we are affecting the <strong>Observable</strong> as a whole and not the single items: for instance, RxLifecycle uses a custom operator in order to make the Subscription end within certain events of the <strong>Activity</strong> or <strong>Fragment</strong> that it’s bound to.</p><p>Now, we need to make most of our Observables run on a new thread and return the result on the main thread but we would need to make a call to <strong>observeOn() </strong>and <strong>subscribeOn()</strong> for each and everyone of them! Even worse, we could create a method that applies the schedulers to a give Observable. But this would be bad, as <a href="http://blog.danlew.net/author/dan-lew/">Dan Lew</a> explains us clearly <a href="http://blog.danlew.net/2015/03/02/dont-break-the-chain/">in his blog post</a>.</p><p>This can be boring, tricky and risky: what if we forget to do it on a very long<br>calculation?</p><p>Once more, we would need to use an interface contained into the Observable class, but this time we are talking about the <a href="http://reactivex.io/RxJava/javadoc/rx/Observable.Transformer.html">Transformer</a> one, which actually relies on a Function that takes as input an <strong>Observable&lt;T&gt;</strong> and returns an <strong>Observable&lt;R&gt;</strong>.</p><p>At this point, what we have to do is just to extend the Transformer interface,<br>apply the Schedulers we want and return the result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/586e187b62746aeaa38c8ff00fee1414/href">https://medium.com/media/586e187b62746aeaa38c8ff00fee1414/href</a></iframe><h4>Wrap up</h4><p>First of all, let’s check how we would use the two operators we just created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083ae508c1782c5d6795c82f0d2120ba/href">https://medium.com/media/083ae508c1782c5d6795c82f0d2120ba/href</a></iframe><p>The <strong>lift()</strong> call is the one that executes our <strong>Sequence</strong> operator that calculates<br>the square root of a give integer, while the <strong>compose()</strong> method is the one providing the <strong>Transformer</strong> that applies the <strong>Schedulers</strong>.</p><p>This would be all but remember that, when creating custom Sequence operators, you need to worry about a wide variety of issues (like <em>backpressure</em>) you may encounter and you have to be prepared to face them, while the Transformers can come handy much more frequently, as they can change the source Observable <em>only through existing operators</em> and have far less risks correlated.</p><p>As usual, you can find the source related to this article into the <a href="https://github.com/tiwiz/RxAndroidCrunch/releases/tag/Part7">GitHub repo</a>.<br>Stay tuned and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22be9e95650c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-7-22be9e95650c">Crunching RxAndroid — Part 7</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 6]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-6-6149764b59e?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/6149764b59e</guid>
            <category><![CDATA[rxandroid]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Wed, 20 Jan 2016 09:10:35 GMT</pubDate>
            <atom:updated>2016-01-20T09:10:34.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-5-1dd5fba89058#.wn8zdtpl3"><em>In the previous part of this series</em></a><em>, we took a look on how we could hook to the lifecycle of the Activity or Fragment that is hosting our reactive routine. Now, it’s time to see how we can manage events of the Android system, with the help of a great tool.</em></p><h4>RxBinding</h4><p>Imagine you can avoid all the <strong>verbose structure</strong> needed for attaching listeners to your UI: <em>wouldn’t you do it just for the sake of code readability?</em> Luckily, there’s a library for that, and it’s pretty awesome too. <a href="https://github.com/JakeWharton/RxBinding">RxBinding</a> comes with a plethora of submodules that will help you manage the <strong>events of all the components</strong> provided with the Android SDK, from the standard to the support one, alongside with those provided with the latest Design Library. And there’s a Kotlin version as well!</p><p>The idea behind the library is to provide an <strong>Observable</strong> whenever the event we are interested in is raised. For example, this is what we would do if we were interested in the <em>onClick</em> event of a <em>View</em>:</p><pre>RxView.<em>clicks</em>(fab).subscribe(aVoid -&gt; onFabClicked());</pre><p>Being an <em>Observable</em>, <strong>we can apply every transformation</strong> to the stream of data provided by just using the factory methods provided by the class RxView.</p><p>In a very similar way, we can override the behaviour of our app when the <em>navigation icon</em> (the one at the top-left corner of an Activity that has a parent) is tapped on by invoking the needed method:</p><pre>RxToolbar.<em>navigationClicks</em>(toolbar).subscribe(aVoid -&gt; onToolbarNavigationClicked());</pre><h4>Further explorations</h4><p>Let’s now focus on what we would do in order to <a href="http://developer.android.com/guide/topics/ui/menus.html#RespondingOptionsMenu">respond to the tap event on a menu item</a> onto the toolbar and let’s compare it with what RxBinding gives us:</p><pre>RxToolbar.<em>itemClicks</em>(toolbar).subscribe(this::onToolbarItemClicked);</pre><p>Simple, isn’t it? Now, for the final example, we will attach a <strong>TextWatcher</strong> to an <em>EditText</em> in the very old way, so that we can be notified of text changes in the given <em>View</em>:</p><pre>usualApproachEditText.addTextChangedListener(new TextWatcher() {</pre><pre>  @Override<br>  public void beforeTextChanged(CharSequence s, int start, int    count, int after) {}<br><br>  @Override<br>  public void onTextChanged(CharSequence s, int start, int before, int count) {<br>    onNewTextChanged(s);<br>}<br><br>  @Override<br>  public void afterTextChanged(Editable s) {}<br>});</pre><p>It is verbose indeed! Can we do something about it? Let’s give it a try!</p><pre>RxTextView.<em>textChanges</em>(reactiveApproachEditText).subscribe(this::onNewTextChanged);</pre><h4>Conclusion</h4><p><a href="https://github.com/JakeWharton/RxBinding">RxBinding</a> is a powerful tool that will help you make your code more readable and, even more important, will allow you to manipulate <strong>Observables</strong> whenever the relevant events are raised.</p><p>As usual, you can find the source related to this article <a href="https://github.com/tiwiz/RxAndroidCrunch">on GitHub</a>.</p><p><em>Thanks to my friends </em><a href="https://twitter.com/workingkills"><em>Eugenio</em></a><em> and </em><a href="https://twitter.com/rotxed"><em>Sebastiano</em></a><em> for proofreading this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6149764b59e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-6-6149764b59e">Crunching RxAndroid — Part 6</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 5]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-5-1dd5fba89058?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/1dd5fba89058</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Fri, 18 Dec 2015 10:03:12 GMT</pubDate>
            <atom:updated>2015-12-18T10:03:12.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><h3>Crunching RxAndroid — Part 5</h3><p><em>In the last episode, we saw that even with the help of Reactive Programming, we risk to leak some important (and heavy) parts of our app, thus wasting users’ resources. They won’t be happy. We won’t be happy as a consequence, so let’s fix this!</em></p><h4>RxLifecycle</h4><p>The guys at Trello faced this issue a while ago and decided to help by releasing in the wild <a href="https://github.com/trello/RxLifecycle">RxLifecycle</a>, an Android library that will automatically manage the unsubscribe routine based on the lifecycle of the target Activity, helping us avoiding leaks. This has the small drawback of having to extend one of the <strong>RxActivity</strong>, <strong>RxAppCompatActivity</strong>, <strong>RxFragment</strong> (with a support version as well) or to provide the <strong>Observable</strong> ourselves for either <strong>ActivityEvent</strong> or <strong>FragmentEvent</strong>.</p><p>It doesn’t matter which way you decide to go. Whichever component you pick, the final implementation won’t be much different. What matters is that, thanks to <strong>RxLifecycle</strong>, our <strong>Observable</strong> lifespan will be bound to that of the Activity or Fragment it’s used into: this means that our Observable will be unsubscribed in the corresponding “closing” lifecycle event to the one that it was subscribed into. For instance, if you start the <strong>Observable</strong> in the <strong>onResume</strong> phase, RxLifecycle will make sure that your <strong>Observable</strong> will be unsubscribed in the <strong>onPause</strong> event of the component it was bound to.</p><h4>The watch begins</h4><p>Let’s imagine that we want to implement a routine that checks that we do not receive any warning while the <strong>Activity</strong> it’s declared into is still running, stopping when the hosting component goes reaches the <strong>onPause</strong> event of the lifecycle. We will then use an interval in order to keep the <strong>Observable</strong> running while the <strong>Activity</strong> is up:</p><pre>Observable.interval(1, TimeUnit.SECONDS)<br> .observeOn(AndroidSchedulers.mainThread())<br> .subscribe(this::logOnNext,this::logOnError,this::logOnCompleted);</pre><p>Let’s run this code and see what shows up in logcat:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAFAgUOVFgIKaTKUmzHK0Q.png" /><figcaption>The onPause method of the Activity is the one announcing that the sun is rising</figcaption></figure><p>Something looks fishy here: our <strong>Observable</strong> keeps on running forever, even if our <strong>Activity</strong> is being killed!</p><h4>The watch shall end</h4><p>To make this code work properly, we need to make the <strong>Observable</strong> aware of the lifecycle of the component that is hosting it.</p><p>One would expect that the library helps us by calling the unsubscribe routine on the <strong>Subscription</strong>, but this would merely end the emission. RxLifecycle will instead call the <strong>onCompleted</strong> method on the <strong>Observable</strong>, and this usually works fine in most of the cases.</p><p>The first thing we have to do is importing the libraries into our build.gradle file:</p><pre>dependencies {<br>    ...<br>    compile &#39;com.trello:rxlifecycle:0.4.0&#39;<br>    compile &#39;com.trello:rxlifecycle-components:0.4.0&#39;<br>}</pre><p>After successfully building the project, we can start using the library. What we need is something emitting the events of our components, so that we can invoke the completion method at the right time. RxLifecycle will allow us to do it in several ways, from emitting the lifecycle events manually to subclass a component that takes care of that for us.</p><p>We will take this latter path and extend the <strong>RxAppCompatActivity</strong>:</p><pre>public class Part5Activity extends RxAppCompatActivity</pre><p>At this point, we can use the compose operator in order to bind it to the lifecycle. We could do this automatically or binding it explicitly to an event by invoking the <strong>bindUntilActivityEvent</strong> static method. By using the first approach, we would simply write:</p><pre>Observable.<em>interval</em>(1, TimeUnit.<em>SECONDS</em>)<br> .observeOn(AndroidSchedulers.<em>mainThread</em>())<br> .compose(bindToLifecycle())<br> .subscribe(this::logOnNext, this::logOnError,this::logOnCompleted);</pre><p>Running the sample now will actually fix the issue and prevent our <strong>Observable</strong> from leaking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezWLmo8Vryrz2YdIda5APQ.png" /><figcaption>The onCompleted method is called when needed</figcaption></figure><p>As usual, you can find the source code for this example on the <a href="https://github.com/tiwiz/RxAndroidCrunch">GitHub repo</a>.</p><p><em>A huge thanks to my friends Sebastiano Poggi, Sebastiano Gottardo and Mark Allison for proof reading this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dd5fba89058" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-5-1dd5fba89058">Crunching RxAndroid — Part 5</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 4]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-4-b2c3771ad52d?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/b2c3771ad52d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[rxandroid]]></category>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Fri, 11 Sep 2015 20:53:58 GMT</pubDate>
            <atom:updated>2015-09-11T20:53:57.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><h4>Learning Reactive Programming the easy way</h4><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-3-91fc9a619b7b"><em>In the previous article</em></a><em>, we saw how to use Reactive Programming in a real word app, but we did not need anything else other than RxAndroid… what if we actually do need something else, combined with this amazing technology?</em></p><h4>Retrofit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dmj_qUt7eEWcxoBEmnY2dg.png" /><figcaption>This is more or less what we want to obtain</figcaption></figure><p>Most probably, you all have at least heard about <a href="http://square.github.io/retrofit/">Retrofit from Square</a>, that is the standard de facto for what concerns the integration of <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">REST</a> APIs within Android apps. Close to its second release (if you haven’t hear about it, take a look to Jake Wharton’s presentation on <a href="https://speakerdeck.com/jakewharton/simple-http-with-retrofit-2-droidcon-nyc-2015">Speaker Deck</a>), this library comes with the goal of <strong>making your networking calls </strong>(both synchronous and asynchronous)<strong> without any boilerplate, though clever use of Java annotations</strong>.</p><p>We obviously want to make asynchronous calls (as we already established, blocking the main thread is evil™ and it will make your app crash), noticing that you can either provide a callback to the framework, to be executed when the call ends or… <strong>make the call itself return an Observable!</strong></p><p>So, as of now, we can imagine that Retrofit works pretty well with RxAndroid (but this is something we read on the documentation!) and we want to see with our own eyes if there is any <em>dark magic</em> involved in making these libraries get along.</p><h4>First steps</h4><p>Let’s start right away by <strong>adding the Gradle dependency</strong> to our project and <a href="http://stackoverflow.com/questions/19932793/syncing-android-studio-project-with-gradle-files/19932896#19932896">synchronising the file</a>, so that the library is downloaded and ready to use:</p><pre>compile &#39;com.squareup.retrofit:retrofit:1.9.0&#39;</pre><p>Now that we have our environment ready, we have to understand a little bit what are the different parts of our implementation of Retrofit: first of all, we need an <strong>endpoint</strong>, that will be the URL to which we are going to make our requests; for this test, I decided to use GitHub’s API (<a href="https://api.github.com/">available here</a>), so that our base URL would be</p><pre>https://api.github.com</pre><p>At this point, we can <strong>declare the interface</strong> that we need in order to query the remote service. In this declaration, we will <em>create a method for each of the calls</em> we want to be able to make, annotating them with the relative path we want it to forward the request to:</p><pre>@GET(“/users/{user}”) <br>Observable&lt;GitHubUser&gt; getUserData(@Path(“user”) String user);</pre><p>Let’s dive into these two lines: in the first one, we have the <strong>annotation</strong> that will tell Retrofit that we want to make a <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods">GET request</a> at the path… but wait! There a strange substring in there, within a couple of curly brackets! That is a variable: we are telling Retrofit that in place of that <em>{user}</em>, we want the String we pass to the method as parameter, the one String that we mark with the <em>@Path(“user”) </em>annotation.</p><p>As an example, if we call</p><pre>getUserData(&quot;tiwiz&quot;)</pre><p>we are telling Retrofit to make a request to</p><pre>https://api.github.com/users/tiwiz</pre><p>The last part of this call is the <strong>return type</strong> and, as we can see, it is set to be an Observable: in this way, we do not need to think to provide a callback, as we can easily subscribe to the call and await for its return.</p><p>At the end of the day, our interface for two calls would look like this, with the different parts that we already explored:</p><pre>public interface GitHubService {</pre><pre>String ENDPOINT = “https://api.github.com&quot;; </pre><pre>@GET(“/users/{user}”) <br>Observable&lt;GitHubUser&gt; getUserData(@Path(“user”) String user); </pre><pre>@GET(“/users/{user}/repos”) <br>Observable&lt;GitHubRepo[]&gt; getRepoData(@Path(“user”) String user);</pre><pre>}</pre><p>Now, we have to <strong>create the Retrofit service that will make the calls</strong> when we need it. In order to do so, we can use the fluid syntax of the appropriate builder:</p><pre>RestAdapter adapter = new RestAdapter.Builder()<br> .setEndpoint(ENDPOINT)<br> .build();</pre><pre>GitHubService gitHubService = adapter.create(GitHubService.class);</pre><p><strong>Note:</strong> starting from version 2.0.0, as of the time of writing, you could find yourself using something like (this is still in development, though)</p><pre>Retrofit retrofit = new Retrofit.Builder()<br>    .baseUrl(ENDPOINT)<br>    .build();<br><br>GitHubService gitHubService = retrofit.create(GitHubService.class);</pre><h4>Making the call</h4><p>Once we declared the service and the interface, we can think about using the API: as an example, I took a few friends of mine and I wanted to know some of the data they stored on GitHub.</p><p>To do so, we firstly <strong>emit each one</strong> of them:</p><pre>Observable.from(interestingUsers)</pre><p>then, we chain the call, using a <a href="http://reactivex.io/documentation/operators/flatmap.html">flat map</a> operator to change the type of the Observable itself:</p><pre>Observable.from(interestingUsers)<br> .flatMap(gitHubService::getUserData)</pre><p>As we already saw in a previous article, the <em>method reference</em> is the equivalent of the following <em>lambda expression</em></p><pre>user -&gt; githubService.getUserData(user)</pre><p>that is the shorted version of the <a href="http://reactivex.io/RxJava/javadoc/rx/functions/Func1.html">Func1</a> declared as:</p><pre>new Func1&lt;String, Observable&lt;GitHubUser&gt;&gt;() {<br> <a href="http://twitter.com/Override">@Override</a> public Observable&lt;GitHubUser&gt; call(String user) {<br> return githubService.getUserData(user);<br> }<br>}</pre><p>We are almost done and what we need to deal with delivering the result on the main thread:</p><pre>.observeOn(AndroidSchedulers.mainThread())</pre><p>and use our <a href="https://github.com/tiwiz/RxAndroidCrunch/blob/master/app/src/main/java/it/tiwiz/rxjavacrunch/part4/model/GitHubUser.java">GitHubUser</a> data in the <a href="https://github.com/tiwiz/RxAndroidCrunch/blob/master/app/src/main/java/it/tiwiz/rxjavacrunch/part4/utils/GitHubWrapper.java">Subscriber</a>.</p><h4>Conclusion</h4><p>We managed to use Retrofit with RxJava and it was fairly easy but, as we used it in the example (that you can find on <a href="https://github.com/tiwiz/RxAndroidCrunch/releases/tag/Part4">GitHub</a>), there are a <strong>couple of open points worth exploring</strong> in the future, one of which being the possibility of leaking stuff if the user quits the Activity before the Retrofit request is finished. <em>Stay tuned for scenes from next episode…</em></p><h4>Fun fact</h4><p>What makes Retrofit work in this very elastic way, is one very powerful Java feature called <a href="http://www.javaworld.com/article/2076233/java-se/explore-the-dynamic-proxy-api.html">Dynamic Proxy Class</a>, which lets a class implement a list of interfaces specified at runtime. If you wish to know more about this interesting, feel free to take a look to <a href="http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html">this article</a> and <a href="http://www.javaspecialists.eu/archive/Issue005.html">this issue</a>.</p><h4>Thanks</h4><p><em>to my friends </em><a href="https://twitter.com/workingkills"><em>Eugenio Marletti</em></a><em>, </em><a href="https://twitter.com/seebrock3r"><em>Sebastiano Poggi</em></a><em>, </em><a href="https://twitter.com/Mariuxtheone"><em>Mario Viviani</em></a><em>, </em><a href="https://twitter.com/rotxed"><em>Sebastiano Gottardo</em></a><em> and </em><a href="https://blog.stylingandroid.com/"><em>Mark Allison</em></a><em> for letting me use their data for the example and for proof reading this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c3771ad52d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-4-b2c3771ad52d">Crunching RxAndroid — Part 4</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 3]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-3-91fc9a619b7b?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/91fc9a619b7b</guid>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Tue, 11 Aug 2015 08:58:15 GMT</pubDate>
            <atom:updated>2015-08-11T08:58:03.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><h4>Learning Reactive Programming the easy way</h4><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-2-fb2a86f4fb8d"><em>In the previous article</em></a><em>, we introduced ourselves to the lambdas, anonymous functions that can make our whole code look much cleaner, simpler and more beautiful… but how can we use this bunch of knowledge in a real life project?</em></p><h4>The starting point</h4><p>Lately, I released a new version of <a href="http://tiwiz.github.io/WhatSong/">WhatSong</a>, an app that once started as <a href="https://github.com/romannurik/dashclock">DashClock</a> extension and it’s now a hub for creating shortcuts for the most famous music recognition providers (such as <a href="http://www.shazam.com/">Shazam</a>) available on Android.</p><p>If you wish to try it, just head over the Play Store link and download it, it’s free!</p><figure><a href="https://play.google.com/store/apps/details?id=it.tiwiz.whatsong"><img alt="" src="https://cdn-images-1.medium.com/max/172/1*L9Vk_vaTJexgF8JGvZCmDg.png" /></a><figcaption>Download WhatSong from the Google Play store</figcaption></figure><p>During the development of this app, I had the need of <strong>knowing which of the supported providers were installed on the device</strong>, so that the users could only choose between a few valid alternatives, or use the Google Now recognition service (since the app is only available within the Play Store, it is <em>a fair assumption</em> to believe that Google Now is always installed).</p><h4>The algorithm</h4><p>Let’s tackle down the sequence of steps we have to take in order to understand <strong>how</strong> to refactor the code:</p><ul><li>take the list of supported providers</li><li>for each of the providers, check if they are installed</li><li>if they are not, remove it from the list</li><li>return the list of installed (and supported) providers</li></ul><p>Since this task could be called any number of times and the list of installed providers could change, I decided, back in the days, to use an <a href="https://developer.android.com/reference/android/app/IntentService.html">IntentService</a> to provide the requested information. You can see the full source code of this class on <a href="https://github.com/tiwiz/WhatSong/blob/master/app/src/main/java/it/tiwiz/whatsong/SearchInstalledProvidersService.java">GitHub</a> or on <a href="http://pastebin.com/qTqndMFy">PasteBin</a>.</p><h4>Rx-ify all the things!</h4><p>Now, we know the steps we have to take, and we have more than 100 lines of IntentService to play with… let’s see if we can make it Reactive!</p><p>First, we have to change a little bit the way we are thinking the algorithm: we begin with <strong>emitting one after the other</strong> all the packages of the music recognition softwares we support:</p><pre>Observable.from(softwarePackages)</pre><p>Then, we create another Observable with the software names, so that we can combine them to create a <a href="https://github.com/tiwiz/WhatSong/blob/develop/app/src/main/java/it/tiwiz/whatsong/utils/PackageData.java">PackageData</a> object:</p><pre>softwareNamesObservable = Observable.from(softwareNames);</pre><p>Now that we have the two Observables emitting the list of packages and names, we can combine them, using the <a href="http://reactivex.io/documentation/operators/zip.html">ZipWith operator</a>, that takes the second Observable and <em>combines</em> it with the first one using the <strong>function</strong> provided as second parameter. In this case, our function will just create a new <a href="https://github.com/tiwiz/WhatSong/blob/develop/app/src/main/java/it/tiwiz/whatsong/utils/PackageData.java">PackageData</a> and we could rewrite this behaviour as a <strong>method reference</strong> pretty easily:</p><pre>Observable.from(softwarePackages)<br>          .zipWith(softwareNamesObservable, PackageData::new)</pre><p>At this point, we have an Observable emitting <a href="https://github.com/tiwiz/WhatSong/blob/develop/app/src/main/java/it/tiwiz/whatsong/utils/PackageData.java">PackageData</a>s, but we are not filtering the results in any way. To do so, we have to first find the operator we need: in this case, I used the <a href="http://reactivex.io/documentation/operators/filter.html">filter</a> one, that will take as argument a <strong>function</strong> and will return a boolean: in case this return value it’s true, the chain keeps on going, otherwise it will be interrupted.</p><p>Let’s define a condition that will return <strong>true</strong> if the given <a href="https://github.com/tiwiz/WhatSong/blob/develop/app/src/main/java/it/tiwiz/whatsong/utils/PackageData.java">PackageData</a> is installed on the device:</p><pre>private static boolean isAppInstalled<br>                   (final Context context, String packageName) {</pre><pre>    boolean isAppInstalled = true; <br>    try { <br>        context.getPackageManager().getPackageInfo<br>                (packageName, PackageManager.GET_ACTIVITIES); <br>    } catch (Exception e) { <br>        isAppInstalled = false; <br>    } <br>    return isAppInstalled; <br>}</pre><p>Now that we have our function, we can just apply it to our Observable, so that we only get the installed packages:</p><pre>Observable.from(softwarePackages)<br>          .zipWith(softwareNamesObservable, PackageData::new)<br>          .filter(packageData -&gt;<br>             isAppInstalled(context, packageData.getPackageName()))</pre><p>The rest of this part is just executing this chain on the <strong>I/O Scheduler</strong> and return it on the <strong>UI Thread</strong>:</p><pre>Observable.from(softwarePackages)<br>          .zipWith(softwareNamesObservable, PackageData::new)<br>          .filter(packageData -&gt;<br>             isAppInstalled(context, packageData.getPackageName()))<br>          .subscribeOn(Schedulers.io())<br>          .observeOn(AndroidSchedulers.mainThread());</pre><p>We are now able to successfully filter the list of supported and installed providers on our device on a background thread and have it delivered on the main thread… we just need to use it! What we need now it’s a simple Subscriber, that will take the result of the Observable and will use it in some way: in the WhatSong app, we decided to just <strong>add each and everyone of the installed apps to an internal list</strong> (when the <em>onNext</em> event was triggered), that would be then converted into an array when the Observable completed its work.</p><pre>.subscribe(Subscribers.create(<br>    (installedApps::add),<br>    (thowable -&gt; { /* on error */ }), <br>    (this::convertInstalledAppsListToVector) ));</pre><h4>Conclusion</h4><p>We just saw how we could refactor an existing project and make use of the Reactive Programming in our every day routine, but this is not the end of the journey, we can apply this ideas in many different ways!</p><p>If you feel like studying a bit more the code we just explained, head over to the <a href="https://github.com/tiwiz/WhatSong">GitHub repo</a>, with a deeper focus to the <a href="https://github.com/tiwiz/WhatSong/blob/develop/app/src/main/java/it/tiwiz/whatsong/mvp/ShortcutPresenter.java">ShortcutPresenter</a> and <a href="https://github.com/tiwiz/WhatSong/blob/develop/app/src/main/java/it/tiwiz/whatsong/utils/InstalledAppsUtils.java">InstalledAppsUtils</a> classes, where this code is effectively used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91fc9a619b7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-3-91fc9a619b7b">Crunching RxAndroid — Part 3</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 2]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-2-fb2a86f4fb8d?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/fb2a86f4fb8d</guid>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Fri, 26 Jun 2015 19:42:06 GMT</pubDate>
            <atom:updated>2015-06-26T19:42:06.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><p>Learning Reactive Programming the easy way</p><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-1-4ac7b7123238"><em>In the last episode</em></a><em>, we started dividing our code into different Actions and Functions, abstracting ourselves from the callback hell we could have gotten into but (there’s always a catch) we can push this refactoring to a whole new level using a feature inherited directly from Java 8…</em></p><h3>Lambdas!</h3><p>Well, what are lambdas? Let’s see what Wikipedia says about them:</p><blockquote>In computer programming, an <strong>anonymous function</strong> (also function literal or lambda abstraction) is a function definition that is not bound to an identifier.</blockquote><p>So, we can say that <strong>lambdas are anonymous functions that RetroLambda converts into optimized anonymous inner classes, enhancing the readability of our code. </strong>What is the form of a lambda, though? Pretty simple! Having <em>parameter</em> to be the input parameter of our <strong>function</strong>, we can picture it up more or less like this</p><pre><em>parameter</em> -&gt; <strong>functionThatWillReturnSomethingUsingThe</strong>(<em>parameter</em>)</pre><h3>Why are lambdas even mentioned?</h3><p>While not really correlated to RxAndroid, lambdas are constructs that get along very well with functional programming: <em>they reduce the amount of code we write and help us in further avoiding the callback hell</em>, one of the reasons why we started using RxAndroid in the first place. Moreover, as aforementioned, they are in fact anonymous inner classes, optimized with the use of Singleton in case of stateless functions, thus avoiding multiple allocations when unnecessary: this alone make them valuable and powerful allies!</p><p>We now know what is a lambda and why we are using them, but we still need <em>something</em> in order to use it, like installing Java 8 and linking the dependency of the correct libraries.</p><h3>Checking Java 8 installation</h3><p>Chances are that, if you are using lambdas for the first time, you are running a Java 7 instance and you need to install the new release of the compiler from the <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html">Sun website</a> or using <a href="https://stackoverflow.com/questions/24342886/how-to-install-java-8-on-mac/28635465#28635465">Homebrew</a> if you are on Mac OS X. Otherwise, just make sure you have the right version of Java on your computer by typing in a shell window the command</p><pre>java -version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*CDIV1BswdAX-NBeIk_b2Ug.png" /></figure><p>and checking you have as output something like this.</p><h3>Introducing RetroLambda</h3><p>The next step would be to <strong>add the Maven Central repository and classpath</strong> to the root <em>build.gradle</em> file of your project in order to start using <a href="https://github.com/orfjackal/retrolambda">RetroLambda</a>, the library that will translate for us the lambda expressions into something Android can understand:</p><pre>buildscript {<br>    repositories {<br>        ...<br>        mavenCentral()<br>    }<br>    dependencies {<br>        ...<br>        classpath &#39;me.tatarka:gradle-retrolambda:3.1.0&#39;<br>    }<br>}</pre><p>Now, we have to <strong>apply the RetroLambda plugin</strong> in the <em>build.gradle</em> file of the modules in which we want to use these features, right next to the Android one we previously declared:</p><pre>apply plugin: &#39;me.tatarka.retrolambda&#39;</pre><p>Android Studio now has to understand we are going to use the new Java 8 syntax, and we will specify it by adding the proper <em>compile options</em> in the <em>android section</em> of the build script</p><pre>android {<br>    ...<br>    compileOptions {<br>        sourceCompatibility JavaVersion.VERSION_1_8<br>        targetCompatibility JavaVersion.VERSION_1_8<br>    }<br>}</pre><p>Finally, we just tell RetroLambda <strong>where</strong> are located the SDKs it needs to <em>translate the Java 8 code we write in the Java 7/ Java 6 byte code Android understands</em>:</p><pre>retrolambda {<br>    jdk System.getenv(&#39;JAVA8_HOME&#39;)<br>    oldJdk System.getenv(&#39;JAVA7_HOME&#39;)<br>}</pre><p>If you are on Mac OS X, though, this last step can give you <strong>quite a headache</strong> if you find yourself facing this message in the Gradle console:</p><pre>Error:Execution failed for task ‘:app:compileDebugJava’.<br> &gt; When running gradle with java 6 or 7, you must set the path to jdk8, either with property retrolambda.jdk or environment variable JAVA8_HOME</pre><p>Luckily, <a href="https://twitter.com/workingkills">thanks to my friend and Gradle Guru Eugenio</a>, we have a handy solution: <a href="https://gist.github.com/Takhion/5c0f6c0c5aba9db5a488">in his Gist</a>, he wrote a function that will query the Java installation, asking for the path of the version we submitted as a input parameter.</p><p>We are now up and running, ready to…</p><h3>Refactor all the things!</h3><p>Let’s start from the code we already wrote and let’s take the <strong>Action1</strong> that sets a String s as a text in the given TextView:</p><pre>Action1&lt;String&gt; textViewOnNextAction = new Action1&lt;String&gt;() {<br>    @Override<br>    public void call(String s) {<br>        txtPart1.setText(s);<br>    }<br>};</pre><p>From this snippet, we will extract the only truly important line and refactor it as a lambda:</p><pre>s -&gt; txtPart1.setText(s)</pre><p>Most probably, Android Studio will promptly suggest to you to <em>transform this lambda expression into something else</em>, using <a href="https://blog.idrsolutions.com/2015/02/java-8-method-references-explained-5-minutes/">method references</a>.</p><p>What are then these <strong>method references</strong>? We can say they are pretty much the same as lambdas, but method references add some readability when the lambda is doing nothing more than <strong>calling a known method of a given class or object with the same parameters the lambda has been invoked with</strong>.</p><p>Our code will then be transformed into:</p><pre>txtPart1::setText</pre><p>as we are just invoking the <em>setText(String s)</em> method of the txtPart1 object.</p><p>Can we do the same trick for something else? Sure thing! Let’s try with a <strong>function</strong>, and the one that will get the single words and emit them one by one looks like a valid candidate:</p><pre>Func1&lt;List&lt;String&gt;, Observable&lt;String&gt;&gt; getUrls = new Func1&lt;List&lt;String&gt;, Observable&lt;String&gt;&gt;() {<br>    @Override<br>    public Observable&lt;String&gt; call (List&lt;String&gt; strings) {<br>        return Observable.<em>from</em>(strings);<br>    }<br>};</pre><p>The important line here is the one we use to create an <strong>Observable</strong> from a list of String. Extracting it to a lambda will transform it into something way shorter and more readable:</p><pre>strings -&gt; Observable.from(strings)</pre><p>But we can go even further!</p><pre>Observable::from</pre><p>With the same logic, <em>we can extract all our functions to lambdas and convert them into method references</em>, so that we have them going from these:</p><pre>s -&gt; showToastWith(s)<br>s -&gt; s.toUpperCase()</pre><p>to these:</p><pre>this::showToastWith<br>String::toUpperCase</pre><p>and all with the help of Android Studio!</p><h3>TL;DR</h3><p>We introduced RetroLambda, lamba expressions and method references, being able easily to make our code much shorter and more readable, resulting in something really as beautiful as:</p><pre>Observable.<em>just</em>(&quot;Hello, World!&quot;)<br>        .observeOn(AndroidSchedulers.<em>mainThread</em>())<br>        .map(String::toUpperCase)<br>        .subscribe(txtPart1::setText);</pre><pre>Observable.<em>from</em>(manyWords)<br>        .observeOn(AndroidSchedulers.<em>mainThread</em>())<br>        .subscribe(message -&gt; Toast.<em>makeText</em>(context, message, Toast.<em>LENGTH_SHORT</em>).show());</pre><pre>Observable.<em>just</em>(manyWordList)<br>        .observeOn(AndroidSchedulers.<em>mainThread</em>())<br>        .flatMap(Observable::<em>from</em>)<br>        .reduce((s, s1) -&gt; String.<em>format</em>(&quot;%s %s&quot;, s, s1))<br>        .subscribe(message -&gt; Snackbar.<em>make</em>(rootView, message, Snackbar.<em>LENGTH_LONG</em>).show());</pre><p>As usual, you can find the code related to this article <a href="https://github.com/tiwiz/RxAndroidCrunch/releases/tag/Part3">on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb2a86f4fb8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-2-fb2a86f4fb8d">Crunching RxAndroid — Part 2</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching RxAndroid — Part 1]]></title>
            <link>https://medium.com/crunching-rxandroid/crunching-rxandroid-part-1-4ac7b7123238?source=rss----a5b52759c69b---4</link>
            <guid isPermaLink="false">https://medium.com/p/4ac7b7123238</guid>
            <dc:creator><![CDATA[Roberto Orgiu]]></dc:creator>
            <pubDate>Sun, 17 May 2015 20:10:54 GMT</pubDate>
            <atom:updated>2015-05-17T20:10:54.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWlAzAY20KLLGIyyD_mzZw.png" /></figure><p>Learning Reactive Programming the easy way</p><p><em>During </em><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-intro-c27eb6f009ea"><em>the last episode</em></a><em>, we have been through the very beginning of RxJava and now we are ready to dive into it a little bit more!</em></p><p>First of all, the main goal for today is to <strong>shorten the code</strong> we wrote during the first article so that it gets more understandable when we look at it after a while… let’s start then with creating something that will just set an input String as the text in a <em>TextView</em> we already linked few lines before:</p><pre>Action1&lt;String&gt; textViewOnNextAction = new Action1&lt;String&gt;() {<br>  @Override<br>  public void call(String s) {<br>    txtPart1.setText(s);<br>  }<br>};</pre><p>Analyzing these lines here, we can notice right away that <strong>we did not create a fully qualified subscriber</strong>, but we just instanced something that will happen if and only if we succeed, avoiding the boilerplate associated with the other events we don’t really need this time.</p><p>We don’t really want to just set a label in a <em>View</em>, what we truly need is to make it uppercase, because we want to shout to the world and we can make it using a function, more or less like this one:</p><pre>Func1&lt;String, String&gt; toUpperCaseMap = new Func1&lt;String, String&gt;(){<br>  <a href="http://twitter.com/Override">@Override</a><br>  public String call(String s) {<br>    return s.toUpperCase();<br>  }<br>};</pre><p>At this point we just need to <strong>create a new Observable</strong> and wire all the logic: since we just need to emit a single String once and we are done, we can use a shortcut and create it right away from the <em>Observable</em> static method</p><pre>Observable&lt;String&gt; singleObservable = Observable.just(“Hello, World!”);</pre><p>Now, if <strong>we wire up the Observable, the Function and the Subscriber</strong>, we would see something like this:</p><pre>singleObservable.observeOn(AndroidSchedulers.mainThread())<br>  .map(toUpperCaseMap)<br>  .subscribe(textViewOnNextAction);</pre><p>Can you spot the news here? I’m talking about the <strong>map operator</strong>!</p><h4>Operators</h4><p>In this example, we introduced our first operator that, in this specific case, is a Function from String to String that will allow us <strong>to manipulate the emission of an Observable </strong>before passing it to the ultimate Subscriber. RxJava comes with a ton of different operators that we can use to transform the flow of data in everything we might need!</p><h4>Working with arrays and lists</h4><p>We saw how we can emit a single item but what if we actually wanted to work with a set of entries, emitting them <em>one by one</em>? Starting from the easiest situation possible, we want to take an array of String and show them in a <em>Toast</em>, one at a time, as we were cycling through them.</p><p>Let’s define a Subscriber that will just show a message out of any input String, so we have at least the end of the queue up and running:</p><pre>Action1&lt;String&gt; toastOnNextAction = new Action1&lt;String&gt;() {<br>  <a href="http://twitter.com/Override">@Override</a><br>  public void call(String s) {<br>    Toast.makeText(context, s, Toast.LENGTH_SHORT).show();<br>  }<br>};</pre><p>As we can see, there is nothing really new here, so we can skip directly to the creation of the Observable, that is really similar to what we did in our previous case, but here we can use something that <em>will emit each and every entry</em> of the array, one by one:</p><pre>Observable&lt;String&gt; oneByOneObservable = Observable.from(manyWords);</pre><p>Using <em>from()</em> we are able to send out all the items in our array in the order they appear, <strong>without caring too much about looping</strong> through them! Great!</p><p>Let’s face instead a more difficult case, in which we need to emit a full list on a single shot and then process each and everyone of the elements on its own. First of all, we need to emit the full list, and we know how to do it by the first example, creating a single Observable from the factory method:</p><pre>Observable.just(manyWordList);</pre><p>Then, we need something that takes an Observable and <strong>gives back another Observable</strong>… maybe we have an operator for that!</p><h4>Introducing the flatMap</h4><p>We saw the map operator that can transform something in something else, but it’s not the only thing that comes in handy! We can make use, in this case, of an item that <strong>can transform the emission of an Observable into the emission of another</strong>. The implementation is fairly easy and we can see it in action in the blink of an eye:</p><pre>Func1&lt;List&lt;String&gt;, Observable&lt;String&gt;&gt; getUrls = new   Func1&lt;List&lt;String&gt;, Observable&lt;String&gt;&gt;() {<br>  <a href="http://twitter.com/Override">@Override</a><br>  public Observable&lt;String&gt; call (List&lt;String&gt; strings) {<br>    return Observable.from(strings);<br>  }<br>};</pre><p>Now, we would like instead to merge all the strings in a single item divided by a space to show a nicely formatted message: we can then use the <em>reduce</em> operator, that will take as input a function and <strong>will emit the merged string </strong>once the Observable which it is attached finishes emitting.</p><pre>Func2&lt;String, String, String&gt; mergeRoutine = new Func2&lt;String, String, String&gt;() {<br>  <a href="http://twitter.com/Override">@Override</a><br>  public String call (String s, String s1) {<br>  return String.format(“%s %s”,s, s1);<br>  }<br>};</pre><p>Finally, we can wire everything together and <em>see the magic happen</em>!</p><pre>Observable.just(manyWordList)<br>  .observeOn(AndroidSchedulers.mainThread())<br>  .flatMap(getUrls)<br>  .reduce(mergeRoutine)<br>  .subscribe(toastOnNextAction);</pre><p>If you want to try this example right away, head over to <a href="https://github.com/tiwiz/RxAndroidCrunch/releases/tag/Part2">GitHub</a>, where you can find the latest source code related to this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ac7b7123238" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crunching-rxandroid/crunching-rxandroid-part-1-4ac7b7123238">Crunching RxAndroid — Part 1</a> was originally published in <a href="https://medium.com/crunching-rxandroid">Crunching RxAndroid</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>