<?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[Familiar Android - Medium]]></title>
        <description><![CDATA[Catching up with the latest in Android development - Medium]]></description>
        <link>https://medium.com/tompee?source=rss----be2594f1cff8---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Familiar Android - Medium</title>
            <link>https://medium.com/tompee?source=rss----be2594f1cff8---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:19:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/tompee" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kotlin Symbol Processing: Getting Started]]></title>
            <link>https://medium.com/tompee/kotlin-symbol-processing-getting-started-9859a520290c?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/9859a520290c</guid>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Thu, 10 Feb 2022 00:47:52 GMT</pubDate>
            <atom:updated>2022-02-10T00:47:51.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tIWFEzs2z5B5FKvY" /><figcaption>Photo by <a href="https://unsplash.com/@nategreno?utm_source=medium&amp;utm_medium=referral">Nathaniel Tetteh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>These series of articles hopefully mark my comeback to technical blogging after a brief hiatus and is focused on documenting my findings and humble tips when using the shiny new `Kotlin Symbol Processing` (KSP) API to create code generation libraries. The first part of this series is talking about what KSP is, and how it differs with Java processors and kapt, and how to setup a project. We will use my library called <a href="https://github.com/tompee26/arctic-tern">ArcticTern</a> as a reference.</p><p><strong>What is KSP</strong>?</p><p>According to the <a href="https://kotlinlang.org/docs/ksp-overview.html">Kotlin documentation</a>, it is a compiler plugin API. It can be used to develop solutions that would analyze your Kotlin code and generate outputs such as boilerplate code or full implementation of your program elements. This is preferred over developing custom compiler plugins because the latter requires inherent knowledge about compilers and their implementations are most likely tied to compiler versions.</p><p>The main advantage of using KSP is that it understand Kotlin’s language features. For those people who worked on kapt before, there is a big problem in trying to analyze and generate Kotlin types because it delegates to javac so it outputs Java TypeElements. Kotlin Metadata helped a lot but still, working on Java elements and Kotlin metadata and knowing when and how to use what is not a trivial thing. Other benefits include faster compilation time (if you only use KSP in your project) and the portability as this isn’t only exclusive to JVM.</p><p><strong>Project Structure</strong></p><p>For an annotation processing and code generation library, we would typically need 2 modules, one containing your annotations and Java types, and the other one is your compiler. I mentioned Java types specifically because the compiler module has to be a Java library (plugin: java-library). Unfortunately, I wasn’t able to successfully setup a compiler using an android library module, that’s why if you need android platform types, you are better off creating a new android module. Don’t forget to check out <a href="https://github.com/tompee26/arctic-tern">ArcticTern</a> as reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*oYlq0oaDhfRF-Sx1dGmefg.png" /><figcaption>Typical project structure</figcaption></figure><p><strong>Dependencies</strong></p><p>Now that we have the modules setup, it’s time to import the dependencies. First, include the plugin in the classpath in your project’s build.gradle.kts. Note that there are compatibility requirements against the Kotlin version. Check out the <a href="https://github.com/google/ksp/releases">release page</a> for more information about what version to use.</p><pre>dependencies {<br>    ....<br>    classpath(&quot;com.google.devtools.ksp:com.google.devtools.ksp.gradle.plugin:$version&quot;)<br>}</pre><p>For the compiler, you would need 2 artifacts.</p><pre>&quot;com.google.devtools.ksp:symbol-processing:$version&quot;<br>&quot;com.google.devtools.ksp:symbol-processing-api:$version&quot;</pre><p>There are other dependencies we would need to make life easy and we will add them now as well. First one is the AutoService. All processors must be declared in resources/META-INF explicitly. Using this dependency allows you to annotate the processor implementation and it will automatically add it in that file. Handy indeed. More on this later.</p><pre>&quot;com.google.auto.service:auto-service-annotations:$version&quot;<br>&quot;dev.zacsweers.autoservice:auto-service-ksp:$version&quot;</pre><p>Second stop is KotlinPoet. This library allows us to write Kotlin code and files in a structured manner. Check out the <a href="https://github.com/square/kotlinpoet/releases">release page</a> for the updated version.</p><pre>&quot;com.squareup:kotlinpoet:$version&quot;<br>&quot;com.squareup:kotlinpoet-ksp:$version&quot;</pre><p><strong>Project Setup</strong></p><p>Aside from wiring the project dependencies, it is important to note that generated files from KSP are not automatically added to source path. Use this handy script to include the generated sources to all build types and variants.</p><pre><em>kotlin </em><strong>{<br>    </strong>sourceSets.all <strong>{<br>        </strong>kotlin.srcDir(&quot;build/generated/ksp/$<em>name</em>/kotlin&quot;)<br>    <strong>}<br>}</strong></pre><p>Now we’re all setup and ready to go! Watch out for the next part. For the mean time, you can read my previous articles on annotation processing <a href="https://medium.com/tompee/kotlin-annotations-and-reflection-caa0d73bf39b">here</a> and <a href="https://medium.com/tompee/kotlin-annotation-processor-and-code-generation-58bd7d0d333b">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9859a520290c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/kotlin-symbol-processing-getting-started-9859a520290c">Kotlin Symbol Processing: Getting Started</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dagger for Android: A Detailed Guide]]></title>
            <link>https://medium.com/tompee/dagger-for-android-a-detailed-guide-b7df2f40c044?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/b7df2f40c044</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[tompee]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Wed, 05 Dec 2018 04:46:49 GMT</pubDate>
            <atom:updated>2018-12-05T05:08:04.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6s7X8Uec63Ix624h" /><figcaption>Photo by <a href="https://unsplash.com/@gemini_zucha89?utm_source=medium&amp;utm_medium=referral">Kwang Mathurosemontri</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we will be exploring Dagger2 for Android. For context and refresher on the “Java” way, have a look at my previous article about Dagger 2 basics <a href="https://medium.com/tompee/android-dependency-injection-using-dagger-2-530aa21961b4">here</a> and scopes and subcomponents <a href="https://medium.com/tompee/dagger-2-scopes-and-subcomponents-d54d58511781">here</a>.</p><p>Two of the main reasons why we should use the Dagger version for Android is because it allows you to write less verbose code and it upholds the DI principle that a class should not know anything about how or what it is being injected with. Now what do we mean by that? Consider this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f0717157547234f094c381f449b03df/href">https://medium.com/media/9f0717157547234f094c381f449b03df/href</a></iframe><p>This is a common practice when building subcomponents and injecting. This code is usually placed in an activity or any top-level android framework type because field injection is the way to go for objects instantiated by the framework. The main issue here is that, this class builds its own container so it knows about its injector. Inversion of control states that it should not build its dependencies but rather, some class outside of it.</p><p>Dagger for Android addresses both of these concerns by introducing android framework type injectors and additional annotations. Before we start, lets add dagger for android in our dependencies. I’m using Kotlin so I will be using kapt instead of the annotationProcessor.</p><pre>implementation &quot;com.google.dagger:dagger:$version&quot;<br>implementation &quot;com.google.dagger:dagger-android:$version&quot;<br>implementation &quot;com.google.dagger:dagger-android-support:$version&quot;<br>kapt &quot;com.google.dagger:dagger-compiler:$version&quot;<br>kapt &quot;com.google.dagger:dagger-android-processor:$version&quot;<br>kapt &quot;com.google.dagger:dagger-android-support:$version&quot;</pre><p><strong>Building our Component</strong></p><p>Component building is same as before, with some added modules. Let’s work our way through an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0faf805f25330fcb428817e3c6d64489/href">https://medium.com/media/0faf805f25330fcb428817e3c6d64489/href</a></iframe><p>@Singleton marks the scope of this component. @Component is used to declare that this interface is a component and dagger should implement it. Notice that in the modules, we added AndroidSupportInjectionModule. This will allow us to use the android framework type bindings (Activity, Fragment, Service, etc). This module extends the framework type bindings to support library types. If you do not intend to use the support library, you can use the AndroidInjectionModule instead. We now add a custom component builder to bind the application instance to the container using @BindsInstance. Note that binding the application instance via module also works but is more tedious and more verbose. Finally, we define a method to inject our application instance. This is the only thing we need to define in our activity really, aside from extra application-wide modules needed.</p><p><strong>Injecting the Application</strong></p><p>Before injecting the application, we need to implement some interfaces first.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1066e6287189edb2d0b3d489617706d8/href">https://medium.com/media/1066e6287189edb2d0b3d489617706d8/href</a></iframe><p>Notice that we need to implement new interfaces such as HasActivityInjector, HasServiceInjector and HasFragmentInjector. These declares that our application can inject activities, services and fragments. We will see how later. You therefore need to implement the get injector methods. These injectors can be acquired from the component because our component includes the AndroidSupportInjectionModule. This method (implementing interfaces) is the best way to customize the injection scope of your application. Sometimes, you don’t need to provide an injector for fragments in application because you want your activity to do that. Or you don’t have any services in your application which leaves you with activity injector only. Therefore, you can implement HasActivityInjector only.</p><p>If you don’t care about all these intricacies, there is a less verbose way wherein you can do all those stuff. You can basically inherit DaggerApplication. DaggerApplication implements the following, HasActivityInjector,<br> HasFragmentInjector, HasServiceInjector, HasBroadcastReceiverInjector, HasContentProviderInjector and HasSupportFragmentInjector if using support library so you don’t have to.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bfec8c3a5680f6bb36c08f94991f1eb/href">https://medium.com/media/1bfec8c3a5680f6bb36c08f94991f1eb/href</a></iframe><p>Your application will only contain this amount of code. Your component should also be updated (should now inherit from AndroidInjector).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a83da375a6174dfc93e7b886c01c357/href">https://medium.com/media/3a83da375a6174dfc93e7b886c01c357/href</a></iframe><p>The inject method is also removed because AndroidInjector already defines it.</p><p>Now let’s proceed to activity injection.</p><p><strong>Activity Injection</strong></p><p>Activity injection can be configured in 2 ways, the first one giving you more control but is a whole new level of tedious to write, the second one being extremely simple but less customization.</p><p>Before we check the two approaches, let us define an activity. This activity will be injected with a Warrior instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/659293fb721edf28c4a87761f812bd65/href">https://medium.com/media/659293fb721edf28c4a87761f812bd65/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c8f67455cc47c0a163d8a3c06b4e128/href">https://medium.com/media/7c8f67455cc47c0a163d8a3c06b4e128/href</a></iframe><p>Yes, injection only involves 1 line, AndroidInjection.inject(this). This should be called before super.OnCreate to ensure that injection happens before fragment attachments.</p><p>Now let’s look at the tedious method first. This method requires you to write a subcomponent and attach it to the main component. Let’s work our way through an example.</p><p>First create a module that will provide your application dependencies. This is common to both approaches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/887b4cd5ce0a957e0421fca522cec7d1/href">https://medium.com/media/887b4cd5ce0a957e0421fca522cec7d1/href</a></iframe><p>Now we will create a subcomponent for MainActivity. You will do this for all activities you want to inject.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15f6580c91ca5e41af8a2b4bac5fb938/href">https://medium.com/media/15f6580c91ca5e41af8a2b4bac5fb938/href</a></iframe><p>This subcomponent should contain the scope and the modules required to satisfy the activity’s dependencies. The subcomponent should inherit from AndroidInjector. A custom builder class can be implemented as well.</p><p>Now that we have the subcomponent, it’s time to bind it in the application component. To do this, you need to create an activity module. This activity module can be thought of as a module that provides all activity injectors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c53f75338922fa143a9e8d628fc5ebd/href">https://medium.com/media/6c53f75338922fa143a9e8d628fc5ebd/href</a></iframe><p>This module should include all activity subcomponents you want to bind. For example you have 3 activity subcomponents, list them in the subcomponents and bind them. This module acts as a map of injector factories. We will see its purpose in a moment.</p><p>The last step is to include this ActivityModule in the AppComponent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9abf559498231ef47585f431199406d8/href">https://medium.com/media/9abf559498231ef47585f431199406d8/href</a></iframe><p>Let’s try to visualize the relationships of each classes we just created. I also added other details to give you an idea on how to extend for other framework types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHjiZVDQE1QaDcuCjVkHGQ.png" /></figure><p>AppComponent includes the ActivityModule which is essentially a mapping of classes to their respective injector factories. The injector factories are essentially your subcomponents that is implemented by your activity module.</p><p>This works as follows. When an activity calls AndroidInjection.inject(this), it gets an instance of the DispatchingAndroidInjector&lt;Activity&gt; from the application. This injector, provided by the AndroidSupportInjectionModule, looks for the appropriate injector factory for your activity (if none is defined and mapped, a compile error is encountered), builds it (essentially your subcomponent) and passes your activity for injection.</p><p>With this, all the intricacies of dependency configuration now lays outside the scope of the activity. All your activity has to do now is to call inject and assume the best.</p><p>Now onto the less verbose approach. Be warned that this approach is only applicable if your subcomponents does not require any custom builder (which is most of the time true).</p><p>First we create the same module to satisfy our activity’s dependency.</p><p>Now, instead of creating a subcomponent, we use a different annotation in our ActivityModule, the @ContributesAndroidInjector.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/027049b42ac01d0658cc72eca9fd4f6a/href">https://medium.com/media/027049b42ac01d0658cc72eca9fd4f6a/href</a></iframe><p>This annotation automatically creates a subcomponent for you. Just provide the module implementations and scopes and you’re good to go. The thing to note here is that the binding function should return the same type as the activity you want to be injected.</p><p>One of the not-so-obvious implication of this approach is that since you passed your activity in inject, your component (or subcomponent) now has an instance of your activity and you can therefore use your activity context inside of your MainActivityModule. This approach is helpful when you want an instance of your fragmentManager in your module for example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79fce3052cbfb6ecd8cd0643e11656c3/href">https://medium.com/media/79fce3052cbfb6ecd8cd0643e11656c3/href</a></iframe><p><strong>Fragment Injection</strong></p><p>Fragment injection is similar with activity injection. However, if you are using support library fragment, you use AndroidSupportInjection.inject(this) instead. Injection is done preferably in onAttach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d513b90fdbfe51333e81327c9cb9ddc/href">https://medium.com/media/2d513b90fdbfe51333e81327c9cb9ddc/href</a></iframe><p>The configuration is pretty much the same. You can apply both approaches. Just make sure that you have an instance of the DispatchingAndroidInjector&lt;Fragment&gt; anywhere in your application or host activity.</p><p>You can also localize your FragmentModule inside your host activity module if you don’t want to declare them in your AppComponent directly. Take a look at this sample code.</p><p>Assuming you have a MainFragmentModule that satisfies your fragment’s dependencies, you can use @ContributesAndroidInjector inside your activity module. Note that binding functions must always be an abstract class or an interface. To workaround this, we can use the includes method of module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6313c3b89ea1f5be7ee4bc8bcf226010/href">https://medium.com/media/6313c3b89ea1f5be7ee4bc8bcf226010/href</a></iframe><p>That concludes our Dagger 2 for Android tutorial. The source code for the ContributesAndroidInjector approach can be found <a href="https://github.com/tompee26/DaggerAndroidSimple">here</a>. The subcomponent approach can be found <a href="https://github.com/tompee26/DaggerAndroidTutorial">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7df2f40c044" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/dagger-for-android-a-detailed-guide-b7df2f40c044">Dagger for Android: A Detailed Guide</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava Ninja: Filtering Operators part 2]]></title>
            <link>https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4a3046646c6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[rxjava-ninja]]></category>
            <category><![CDATA[tompee]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Mon, 01 Oct 2018 02:06:59 GMT</pubDate>
            <atom:updated>2018-10-01T02:07:36.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NH7s2YKfahkhjOwV" /><figcaption>“tea filling glass pitcher” by <a href="https://unsplash.com/@wadeaustinellis?utm_source=medium&amp;utm_medium=referral">Wade Austin Ellis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).</p><p>Let us now continue with our discussions of Filtering operators.</p><p><strong>First</strong></p><p><em>first</em> converts the observable to a Single and emits the first item, or a given default value if the source does not emit any items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*eCGeSQ2kfSKruuTC.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/first.s.png">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c395142584e923a520837c304affdea2/href">https://medium.com/media/c395142584e923a520837c304affdea2/href</a></iframe><p>Output:</p><pre>1</pre><p>There is also a variant that converts to a Maybe called <em>firstElement</em>. This emits only the first item emitted by the source. A variant called <em>singleElement</em> also exists which emits the first item but throws an exception if there are more than 1 item.</p><p><strong>ElementAt</strong></p><p><em>elementAt</em> returns a Maybe that emits the element at the specified index. If the source terminates before the specified index, <em>elementAt</em> will simply complete. Indexes are zero based.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*0BHI-f_rMl5HPYaJ.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/elementAt.o.png">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d2d9e43ee50a4abbfdd13bcce6a5fb5/href">https://medium.com/media/2d2d9e43ee50a4abbfdd13bcce6a5fb5/href</a></iframe><p>Output:</p><pre>5</pre><p><strong>Last</strong></p><p><em>last</em> converts an observable to a Single and emits the last item emitted by the source before it completes, or a default value if the source did not emit anything. In other implementations (such as .NET), this is a blocking operator that returns the last value, not an observable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HFnB94E2FiiErW6m.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/last.2.png">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a72760bb614133d565a4be845c2eb1d0/href">https://medium.com/media/a72760bb614133d565a4be845c2eb1d0/href</a></iframe><p>Output:</p><pre>5</pre><p>There is also a variant called <em>lastElement</em> that converts to Maybe. This will simply complete if no items are emitted by the source.</p><p><strong>TakeWhile</strong></p><p><em>takeWhile</em> is a variant of <em>take</em> which emits a value while a given predicate holds true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q8pOGCqNMzKm1wIb.png" /><figcaption><a href="http://reactivex.io/documentation/operators/takewhile.html">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f15ac61f9977c827cb819be545157d2b/href">https://medium.com/media/f15ac61f9977c827cb819be545157d2b/href</a></iframe><p>Output:</p><pre>1<br>2<br>3</pre><p><strong>SkipWhile</strong></p><p><em>skipWhile</em> is a variant of <em>skip </em>that prevents emission while a given predicate holds true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rmymxedmOAQmriJu.png" /><figcaption><a href="http://reactivex.io/documentation/operators/skipwhile.html">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a109199f2acbbcdea6b820c782424c98/href">https://medium.com/media/a109199f2acbbcdea6b820c782424c98/href</a></iframe><p>Output:</p><pre>3<br>4<br>5</pre><p><strong>IgnoreElements</strong></p><p>This operator simply ignores all emissions and emits complete or error events only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X82EoqJVl56E4ffu.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/ignoreElements.2.png">Image from rx wiki</a></figcaption></figure><p>This code outputs nothing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04605f75a1c1d3568ee1908436f6bd34/href">https://medium.com/media/04605f75a1c1d3568ee1908436f6bd34/href</a></iframe><p><strong>Sample</strong></p><p><em>sample</em> is a very powerful operator. It allows you to get the most recent item emitted by the source at specific intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*7SXLx9ieKnIUNWZCG_VyLg.png" /><figcaption><a href="http://reactivex.io/documentation/operators/sample.html">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccb2c8a964b8b04549efa2145ac67008/href">https://medium.com/media/ccb2c8a964b8b04549efa2145ac67008/href</a></iframe><p>Output:</p><pre>1<br>3<br>4<br>7<br>8<br>10<br>13<br>...</pre><p><strong>Debounce</strong></p><p><em>debounce</em> emits the last item after a specified time interval has elapsed since the last emission. In simpler terms, it filters out rapid emission. This is useful in cases such as monitoring text fields for real-time search. When searching, you do not want to trigger a search every time the search text updates. You might want to trigger only after a time interval has passed since the last emission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*5g6dRK8Uq7rMvjTUl8Mjpg.png" /><figcaption><a href="http://reactivex.io/documentation/operators/debounce.html">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16c4360dc265aeb4974a7e49aa3bace5/href">https://medium.com/media/16c4360dc265aeb4974a7e49aa3bace5/href</a></iframe><p>This is not a good example but it demonstrates the function. This will emit:</p><pre>5</pre><p><strong>Distinct</strong></p><p><em>distinct</em> is both powerful and dangerous when used incorrectly. <em>distinct</em> only emits unique values and filters duplicates. Equality is judged using the default <em>Object.equals()</em> and <em>Object.hashCode()</em> methods so be sure to define meaningful comparison logic.</p><p>Internally, <em>distinct</em> uses a HashSet to store the unique references. Distinct does not clear this map until the sequence terminates so this will only grow. Unbounded or infinite streams with very distinct elements may cause this HashSet to grow very large and cause an OutOfMemoryError.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*-6hVxuhomtnVL-0arelHyw.png" /><figcaption><a href="http://reactivex.io/documentation/operators/distinct.html">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8257dd2bc3cb3accc16ffdd932cae511/href">https://medium.com/media/8257dd2bc3cb3accc16ffdd932cae511/href</a></iframe><p>Output:</p><pre>1<br>2<br>3<br>4<br>5</pre><p>There are other variants that improves the default functionality. One variant allows you to provide a key selector function to determine uniqueness. Another variant allows you to provide a collection supplier to control retention policy manually.</p><p><strong>DistinctUntilChanged</strong></p><p>This operator is a special version of the <em>distinct</em> operator. It allows you to emit values that are different from their predecessor. This operator caches the previous emitted item for comparison with the succeeding items. It also uses the default <em>Object.equals()</em> and <em>Object.hashCode() </em>to determine uniqueness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JjrXyx9TOGrx3ZaE.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/distinctUntilChanged.key.png">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/922f0f3b68796c2e423d75b232875b12/href">https://medium.com/media/922f0f3b68796c2e423d75b232875b12/href</a></iframe><p>Output:</p><pre>1<br>2<br>1<br>2<br>3<br>4<br>5</pre><p>There is also a variant wherein you can provide a BiPredicate that receives the previous and current items. This will allow you to determine uniqueness manually.</p><p>That’s it for the Filtering operators. We will now move on with other types of operators on the next articles.</p><p>Check out the other articles in this series.</p><ol><li><a href="https://medium.com/tompee/rxjava-ninja-introduction-to-reactive-programming-4b1e27b20576">Introduction to Reactive Programming</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-building-your-first-observables-and-observers-4e6c4ad9e243">Building your first Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">In Depth Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">Marble Diagrams and Operators</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">Observable Factories Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">Observable Factories Part 2</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">Single, Maybe and Completable</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">Hot and Cold Observables</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">Filtering Operators Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">Filtering Operators Part 2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a3046646c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">RxJava Ninja: Filtering Operators part 2</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava Ninja: Filtering Operators part 1]]></title>
            <link>https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/e7e72b39d70</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[tompee]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava-ninja]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Sat, 08 Sep 2018 02:25:25 GMT</pubDate>
            <atom:updated>2018-10-01T02:09:55.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RZHVLRCQ6Hy4jrrh" /><figcaption>Photo by <a href="https://unsplash.com/@nkalil?utm_source=medium&amp;utm_medium=referral">Najib Kalil</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).</p><p>Now that we’re done with observable factories, it is time to discuss the operators that makes RxJava a powerful tool. There are hundreds of operators available and in this tutorial we will talk about the <em>filtering operators</em>.</p><p>Filtering operators, as the name implies, suppress emissions when a certain condition is not met. The most simple and most common filtering operator is the <em>filter</em>.</p><p><strong>Filter</strong></p><p>The <em>filter</em> operator takes a predicate as input. It will map each emission to a boolean value and emit only those that qualifies as true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*Uaiw2DzhmlDwXOpYXUfmyg.png" /><figcaption><a href="http://reactivex.io/documentation/operators/filter.html">Image from rx wiki</a></figcaption></figure><p>Let’s see an actual example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7a55ad997c0106d7bd50f43bd78479c/href">https://medium.com/media/d7a55ad997c0106d7bd50f43bd78479c/href</a></iframe><p>This will output</p><pre>1<br>2</pre><p><strong>ofType</strong></p><p><em>ofType</em> is similar to filter but instead of accepting a predicate, it accepts a type. It only emits those items that are the same as the specified type, or a subtype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pe9O969C4VVpwn0f.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/ofClass.png">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fbc246f24f126e6a41a4f9e247f7582/href">https://medium.com/media/9fbc246f24f126e6a41a4f9e247f7582/href</a></iframe><p>Output:</p><pre>1<br>12.0</pre><p><strong>Take</strong></p><p>The <em>take</em> operator allows you to limit the emission count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fiMpTQagOjyi8dIu.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/take.png">Image from rx wiki</a></figcaption></figure><p>One overload of the take operator allows you to limit the count. If the observable emits more than the specified limit, the take operator will simply terminate the emission with an onComplete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0ec5ee6d10e1c1881c8f496fe201955/href">https://medium.com/media/f0ec5ee6d10e1c1881c8f496fe201955/href</a></iframe><p>Output:</p><pre>1<br>2<br>3<br>completed</pre><p>If the observable emits fewer items, it will simply emit what is available from the source and terminates as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d6623ee5ffaaca1bdfc7d09581c524b/href">https://medium.com/media/3d6623ee5ffaaca1bdfc7d09581c524b/href</a></iframe><p>Output:</p><pre>1<br>2<br>3<br>4<br>5<br>completed</pre><p>The other overload is time based. It takes all the items emitted within the time window.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae069552b1c64b39a563a239b22b1bfe/href">https://medium.com/media/ae069552b1c64b39a563a239b22b1bfe/href</a></iframe><p>Output:</p><pre>0<br>1<br>completed</pre><p><strong>TakeLast</strong></p><p><em>takeLast</em> is the reverse end of <em>take</em>. It emits the last n items from the upstream observable. To do this, it subscribes to the upstream observable and exhaust its elements before emitting the last n items. Therefore it is important to note that this operator is a stateful one. Infinite upstream sequence will block indefinitely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*NuhcRcHDaI1J_bUGFYDPjA.png" /><figcaption><a href="http://reactivex.io/documentation/operators/takelast.html">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d344a523a12abc5c6493a405087ea21d/href">https://medium.com/media/d344a523a12abc5c6493a405087ea21d/href</a></iframe><p>Output:</p><pre>beforeTakeLast: 1<br>beforeTakeLast: 2<br>beforeTakeLast: 3<br>beforeTakeLast: 4<br>beforeTakeLast: 5<br>beforeTakeLast: 6<br>5<br>6<br>completed</pre><p>takeLast also has a time based. This operator takes note of the time of each emission and emits the last values that are within the specified time duration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43949ed8ce9bfd962d71d96d382449c0/href">https://medium.com/media/43949ed8ce9bfd962d71d96d382449c0/href</a></iframe><p>Output:</p><pre>beforeTakeLast: 0<br>beforeTakeLast: 1<br>beforeTakeLast: 2<br>beforeTakeLast: 3<br>beforeTakeLast: 4<br>beforeTakeLast: 5<br>beforeTakeLast: 6<br>beforeTakeLast: 7<br>beforeTakeLast: 8<br>beforeTakeLast: 9<br>beforeTakeLast: 10<br>beforeTakeLast: 11<br>beforeTakeLast: 12<br>beforeTakeLast: 13<br>beforeTakeLast: 14<br>beforeTakeLast: 15<br>beforeTakeLast: 16<br>beforeTakeLast: 17<br>beforeTakeLast: 18<br>beforeTakeLast: 19<br>15<br>16<br>17<br>18<br>19<br>completed</pre><p><strong>Skip</strong></p><p><em>skip</em> is the opposite of <em>take</em>. It skips the first n emissions and emits the items starting from n + 1, if they exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*Nu90S52umwwqHcqnKnCBZQ.png" /><figcaption><a href="http://reactivex.io/documentation/operators/skip.html">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad34d394535c34d7b0a76508b556d998/href">https://medium.com/media/ad34d394535c34d7b0a76508b556d998/href</a></iframe><p>Output:</p><pre>3<br>4<br>5<br>6<br>completed</pre><p><em>skip</em> also has a time based overload just like take. It skips the emissions within the specified time duration.</p><p><strong>SkipLast</strong></p><p><em>skipLast</em> is the opposite of <em>takeLast</em>. Just like <em>takeLast, </em>it also exhausts the upstream observable and queues the items to be able to logically determine the count of items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*P3Vwgcznzn9ngCjZY6Rc2Q.png" /><figcaption><a href="http://reactivex.io/documentation/operators/skiplast.html">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8730664f277c8136f41444a0bb87c65/href">https://medium.com/media/b8730664f277c8136f41444a0bb87c65/href</a></iframe><p>Output:</p><pre>beforeSkipLast: 1<br>beforeSkipLast: 2<br>beforeSkipLast: 3<br>beforeSkipLast: 4<br>beforeSkipLast: 5<br>beforeSkipLast: 6<br>1<br>2<br>3<br>4<br>completed</pre><p>Similar to <em>takeLast</em>, <em>skipLast</em> has a time based overload as well.</p><p>That’s it for now. There are plenty more filter operators to be discussed so stay tuned.</p><p>Check out the other articles in this series.</p><ol><li><a href="https://medium.com/tompee/rxjava-ninja-introduction-to-reactive-programming-4b1e27b20576">Introduction to Reactive Programming</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-building-your-first-observables-and-observers-4e6c4ad9e243">Building your first Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">In Depth Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">Marble Diagrams and Operators</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">Observable Factories Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">Observable Factories Part 2</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">Single, Maybe and Completable</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">Hot and Cold Observables</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">Filtering Operators Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">Filtering Operators Part 2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7e72b39d70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">RxJava Ninja: Filtering Operators part 1</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava Ninja: Hot and Cold Observables]]></title>
            <link>https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/19b30d6cc2fa</guid>
            <category><![CDATA[tompee]]></category>
            <category><![CDATA[rxjava-ninja]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Mon, 06 Aug 2018 05:57:39 GMT</pubDate>
            <atom:updated>2018-10-01T02:09:43.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pcZ1mhI6IYWn5ADD" /><figcaption>Photo by <a href="https://unsplash.com/@oliver_visuals?utm_source=medium&amp;utm_medium=referral">Easton Oliver</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).</p><p>In today’s article, we will be talking about 2 types of observable, hot and cold observables.</p><p><strong>Cold Observables</strong></p><p>Cold observables are sequences that only emits item upon subscription. Each observer will have its own set of items emitted to them and depending on how the observable was created, will have different instances of emitted items. Let’s see what this looks like by example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d7525a37b658457c46ed0a480ffc2c0/href">https://medium.com/media/3d7525a37b658457c46ed0a480ffc2c0/href</a></iframe><p>An interval observable was subscribed upon by two observers at a different time. Let’s see what this actually does.</p><pre>Observer 1: 0<br>Observer 1: 1<br>Observer 1: 2<br>Observer 1: 3<br>Observer 2: 0<br>Observer 1: 4<br>Observer 2: 1<br>Observer 1: 5<br>Observer 2: 2<br>Observer 1: 6<br>Observer 2: 3</pre><p>Regardless of whether the same observable instance is used, both observers started from 0. This is a cold observable. This happens because a different observable source is being created for each observer. Most convenience factories are by default cold observable factories.</p><p>In reality, data-driven observables are most likely cold. Even those cases wherein the same observable yields different results (like HTTP GET, database query). The idea here is that, the data or operation is being “replayed” to every observer. For those familiar, some real-world examples of cold observables are Retrofit and Room queries.</p><p><strong>Hot Observables</strong></p><p>In contrast to cold observables, hot observables emit items regardless of whether there are observers. In a hot observable, there is a single source of emission and depending on when observers subscribe, they may miss some of those emissions.</p><p>Most common examples of this are UI events. For example in Android, a click event can be represented as an observable. And it is only logical for observers to receive only the events after they subscribed, so the click observable has no need to cache them for replay.</p><p>There are many ways to implement hot observables. One of them is <em>Subjects</em> and we will discuss them in the future when we discuss <em>Multicasting</em> in detail. For now we will use a special type of observable called <em>ConnectableObservable</em>.</p><p><strong>ConnectableObservable</strong></p><p>A ConnectableObservable is a single observable source for different observers. The main difference aside from being a single observable source is that calling subscribe on a ConnectableObserver will not trigger emission, but connect will.</p><p>To convert an observable to a connectable one, you can use the publish operator. Publishing the observable will make it hot and will not replay the items for observers after activation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afdcb8cba3a3aba11a47cb55d8296fc6/href">https://medium.com/media/afdcb8cba3a3aba11a47cb55d8296fc6/href</a></iframe><p>The above code demonstrates how to publish an observable. However, running the code will not emit anything. That is because a connectable observer requires the connect method to be invoked to begin emission. Let’s try subscription at two different time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c5131a2d9d3dac04253afb47635c300/href">https://medium.com/media/1c5131a2d9d3dac04253afb47635c300/href</a></iframe><p>Let’s observe it in action.</p><pre>Observer 1: 0<br>Observer 1: 1<br>Observer 1: 2<br>Observer 1: 3<br>Observer 2: 3<br>Observer 1: 4<br>Observer 2: 4<br>Observer 1: 5<br>Observer 2: 5<br>Observer 1: 6<br>Observer 2: 6<br>Observer 1: 7<br>Observer 2: 7</pre><p>Notice that the observer 2 received the same emission as observer 1 upon subscription. This observable behavior of emitting to all observers simultaneously is called <em>Multicasting</em> and we will visit this feature again in the future. Note that emission will start after connect invocation so it is perfectly valid to setup multiple observers beforehand to synchronize them.</p><p>Calling connect will return a subscription that can be disposed. This implies that individual unsubscription of observers does not affect the connectable observable. Only the disposal of the subscription from connect can actually stop the emission. Now, how do we automate this connect on observer subscription and dispose if there are no active observers anymore?</p><p>There is a method in ConnectableObservable class called refCount that will do just that. refCount returns an observable that will be connected at subscription of an observer and will terminate if there are no more observers. Let’s demonstrate that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71ad24275b474623e8ef1ddc6f2bd14e/href">https://medium.com/media/71ad24275b474623e8ef1ddc6f2bd14e/href</a></iframe><p>Two observers will subscribe at different times and unsubscribe later. Then a third observer will subscribe right after that. Based on the defined behavior of refCount, the observable should have been disposed after unsubscription of the 2 observers. In the 3rd subscription, the observable should be a fresh one already. Let’s verify.</p><pre>Observer 1 subscribed<br>Observer 1: 0<br>Observer 1: 1<br>Observer 1: 2<br>Observer 2 subscribed<br>Observer 1: 3<br>Observer 2: 3<br>Observer 1: 4<br>Observer 2: 4<br>Observer 1 unsubscribed<br>Observer 2 unsubscribed<br>Observer 3 subscribed<br>Observer 3: 0<br>Observer 3: 1</pre><p>So far so good. Also, there are different variants of refCount such as tracking a minimum observer count, timeout before disposal, etc, so choose one to your liking.</p><p>That’s it for hot and cold observables. Remember, data-driven is cold, event-driven is hot.</p><ol><li>I<a href="https://medium.com/tompee/rxjava-ninja-introduction-to-reactive-programming-4b1e27b20576">ntroduction to Reactive Programming</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-building-your-first-observables-and-observers-4e6c4ad9e243">Building your first Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">In Depth Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">Marble Diagrams and Operators</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">Observable Factories Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">Observable Factories Part 2</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">Single, Maybe and Completable</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">Hot and Cold Observables</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">Filtering Operators Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">Filtering Operators Part 2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19b30d6cc2fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">RxJava Ninja: Hot and Cold Observables</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava Ninja: Single, Maybe and Completable]]></title>
            <link>https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/b5907dddc5e4</guid>
            <category><![CDATA[rxjava-ninja]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tompee]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Fri, 03 Aug 2018 07:29:04 GMT</pubDate>
            <atom:updated>2018-10-01T02:09:12.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BIiP-GMynVdZWa12" /><figcaption>“Single daisy blooms in a leafy green landscape” by <a href="https://unsplash.com/@shanerounce?utm_source=medium&amp;utm_medium=referral">Shane Rounce</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).</p><p>In this article, we will talk about special types of Observables. They still follow the observable contract but they are specialized for a specific purpose.</p><p><strong>Single</strong></p><p>Single is an observable that emits only a single item. The factory operators for Single is more or less similar with observables restricted to a single emission. The only noticeable difference is the observer definition. The SingleObserver class is defined below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d1f1657d802de2d09e036436ce82418/href">https://medium.com/media/9d1f1657d802de2d09e036436ce82418/href</a></iframe><p>Notice that there is no more onNext and onComplete and a new notification onSuccess is defined. This makes sense because a Single only emits a single item, hence it can be interpreted as onNext and onComplete at the same time. Let’s see an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e1c846b8a9cbabd9b78c1fdd4c8fb5f/href">https://medium.com/media/5e1c846b8a9cbabd9b78c1fdd4c8fb5f/href</a></iframe><p>The example above creates a Single observable that emits hello. The onSuccess handler prints the item. The output will be</p><pre>hello</pre><p>Now, why is there a need to define a new type for this? Well, the answer lies on the communication of intention. Using Single can communicate, effectively I might add, the nature of the observable. For example, if you need to perform a one time network request, you can create it using Single and users of this observable does not need to look at the implementation details to know what to expect from this observable. Also, some operators just only return a single item so it is easier to express them this way. An example is the first operator which return the first item in the stream, a default value if there are no item in the observable source.</p><p>If there is a need for you to convert a Single to Observable, say for example you want to be notified on both onNext and onComplete, there is an operator just for that. You can use the toObservable. The opposite is also possible. singleOrError converts your Observable to a Single and if there are more than 1 item in the sequence, an exception will be thrown in the onError channel.</p><p><strong>Maybe</strong></p><p>Maybe is similar to Single but this time, it allows your observable the ability to not emit any item at all. The MaybeObserver is defined as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40d4e5daeaa298ea4d2254d5ba1b681c/href">https://medium.com/media/40d4e5daeaa298ea4d2254d5ba1b681c/href</a></iframe><p>There are 4 notifications again, the onComplete is back (to signify no items) and the onSuccess as a combination of onNext and onComplete.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3cb59ed905f8460a9662b8d0abeed90/href">https://medium.com/media/f3cb59ed905f8460a9662b8d0abeed90/href</a></iframe><p>The sample code above will output</p><pre>onComplete<br>hello</pre><p>The first one emits onComplete because no there is nothing to emit. The second one outputs the hello under the onSuccess channel and does not emit an onComplete after. Maybe is also used in many operators to also communicate intention. For example, the first operator requires you to pass a default value in case there is no item. But you can specify it as a Maybe since it can either be an observable with a single item, or no items at all. This is what firstElement does.</p><p>Same with Single, Maybe can also be converted to Observable via the toObservable operator. Unfortunately, there is no straightforward way to convert an Observable to Maybe (unless you are interested in just the firstElement). You can convert it to Single first though and then to Maybe using toMaybe.</p><p><strong>Completable</strong></p><p>This observable is only concerned about two things, if some action is executed or an error is encountered. Let’s check the definition of its observer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a271ebe5a21b875a4c2e98888329f5d7/href">https://medium.com/media/a271ebe5a21b875a4c2e98888329f5d7/href</a></iframe><p>There are only 2 events, onComplete and onError. This is useful for cases wherein you are only interested if something has executed properly, ignoring output or whatever.</p><p>Like the two above, Completable can be converted to an observable using toObservable. However, the reverse is also not straightforward. You can convert to a Single first and use ignoreElement, though if you want (toCompletable is deprecated).</p><p>That’s it for special observables. Next, we will discuss hot vs. cold observables.</p><ol><li>I<a href="https://medium.com/tompee/rxjava-ninja-introduction-to-reactive-programming-4b1e27b20576">ntroduction to Reactive Programming</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-building-your-first-observables-and-observers-4e6c4ad9e243">Building your first Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">In Depth Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">Marble Diagrams and Operators</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">Observable Factories Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">Observable Factories Part 2</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">Single, Maybe and Completable</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">Hot and Cold Observables</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">Filtering Operators Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">Filtering Operators Part 2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5907dddc5e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">RxJava Ninja: Single, Maybe and Completable</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava Ninja: Observable Factories Part 2]]></title>
            <link>https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/e52a78be4cda</guid>
            <category><![CDATA[rxjava-ninja]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tompe]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Thu, 02 Aug 2018 03:52:55 GMT</pubDate>
            <atom:updated>2018-10-01T02:09:02.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o7Wnorfnmh9wvSR4" /><figcaption>Photo by <a href="https://unsplash.com/@mariusmasalar?utm_source=medium&amp;utm_medium=referral">Marius Masalar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).</p><p>Today we will continue our discussion of observable factories. The first family that we will discuss are special because they are “time-based”.</p><p><strong>Observable.timer</strong></p><p>This operator let’s you specify a time delay before emitting an event. This emits a single Long with a value 0L before terminating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*asW_KhGE-qZdsL7L.png" /><figcaption><a href="http://reactivex.io/documentation/operators/timer.html">Image from rx docs</a></figcaption></figure><p>Let’s see some code to demonstrate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7847a2d1f4493b0b90f9c64542268d2/href">https://medium.com/media/a7847a2d1f4493b0b90f9c64542268d2/href</a></iframe><p>What do you think will be the output of the above code when run as is? Well, the most probable one is none. Why is that? Let’s look at the code.</p><p>Calling the timer method will instantiate an ObservableTimer class using a scheduler. Wait what? A scheduler? Yes you read that right. This scheduler will be used to schedule the task. And this scheduler will run in a separate execution context in this case, a computation thread. There are many types of schedulers and they will be discussed soon so don’t worry if some of the terms sound weird to you.</p><p>For now, you can think of using schedulers as executing in a background thread. This explains why there is no log in the above example. The task was scheduled to fire after 1 second but the main thread immediately expired after subscription. We can prove this by adding a thread sleep of 5 seconds after subscribe to prolong the main thread life. Doing so will net you the desired output.</p><pre>0</pre><p>Now, let us check if the runtime thread is really different from assembly or subscription time. Let’s run this code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fde3bb80b0652c7d5a22f552ec4fb54/href">https://medium.com/media/4fde3bb80b0652c7d5a22f552ec4fb54/href</a></iframe><p>The output should not surprise you.</p><pre>Assembly thread: main<br>Subscription thread: main<br>Runtime onNext thread: RxComputationThreadPool-1<br>Runtime completed thread: RxComputationThreadPool-1</pre><p>This means that the subscription still happens in the main thread and the onNext and onCompleted is already triggered in a computation thread. Now what if you want to wait for the result in the main thread? You can use a blockingSubscribe instead. Doing so will net you this log</p><pre>Assembly thread: main<br>Subscription thread: main<br>Runtime onNext thread: main<br>Runtime completed thread: main</pre><p><strong>Observable.Interval</strong></p><p>This operator is similar to the timer but this time with periodic emits. There is also a variant without initial delay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ax-Pz7VaQq3iDSPz.png" /><figcaption><a href="http://reactivex.io/documentation/operators/interval.html">Image from rx docs</a></figcaption></figure><p>Let’s use the same code from timer, replacing it with interval.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a765865d2e28e592eda057dad4052759/href">https://medium.com/media/a765865d2e28e592eda057dad4052759/href</a></iframe><p>The output is</p><pre>Assembly thread: main<br>Subscription thread: main<br>Runtime onNext thread: RxComputationThreadPool-1<br>Runtime onNext thread: RxComputationThreadPool-1<br>Runtime onNext thread: RxComputationThreadPool-1<br>Runtime onNext thread: RxComputationThreadPool-1<br>Runtime onNext thread: RxComputationThreadPool-1</pre><p><strong>Observable.intervalRange</strong></p><p>This operator is under the range family but with interval capability. You can use this to generate a incremental values within a range at a given interval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C_s8JjDAQfqF9Q6L.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/intervalRange.png">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca9035c9e0d76dfa00d6456c4ab3ca5/href">https://medium.com/media/1ca9035c9e0d76dfa00d6456c4ab3ca5/href</a></iframe><p>This will output 5 items as long as the main thread can outlast the computational thread.</p><pre>Assembly thread: main<br>Subscription thread: main<br>Runtime onNext thread: RxComputationThreadPool-1 value: 1<br>Runtime onNext thread: RxComputationThreadPool-1 value: 2<br>Runtime onNext thread: RxComputationThreadPool-1 value: 3<br>Runtime onNext thread: RxComputationThreadPool-1 value: 4<br>Runtime onNext thread: RxComputationThreadPool-1 value: 5<br>Runtime completed thread: RxComputationThreadPool-1</pre><p>Now we will look at another family of factories that does not really create observables from non-observables but repeats an existing observable source.</p><p><strong>Observable.repeat</strong></p><p>This operator repeats the source sequence up to a specified amount of time. If number of times is not specified, it will repeat until Long.MAX_VALUE times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6rkHPnryf6Xsn51U.png" /><figcaption><a href="http://reactivex.io/documentation/operators/repeat.html">Image from rx docs</a></figcaption></figure><p>Note that this operator repeats the entire sequence of its source, not just an item. Let’s see.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c788e0e209de64371c1863372d5fb7f/href">https://medium.com/media/8c788e0e209de64371c1863372d5fb7f/href</a></iframe><p>This will output</p><pre>hello<br>hi<br>hello<br>hi<br>....</pre><p>indefinitely. Note that this does not run on a scheduler. A good way to check if an operator runs on a scheduler is look at the operator function definition and look for the @SchedulerSupport annotation.</p><p>Another thing to note is that repetition is perform via <strong>resubscribing</strong>. This means that if your observable source is created on the fly, it will emit different instances of items from every repeat. Let’s try this on a callable that returns the current time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f4458cd409cd6f633ea0930a40a3820/href">https://medium.com/media/6f4458cd409cd6f633ea0930a40a3820/href</a></iframe><p>This will output different timestamps depending on resolution. Try it.</p><p><strong>Observable.repeatUntil</strong></p><p>This operator will repeat the source indefinitely until the a condition is satisfied. This is kind of counter-intuitive as you would expect a repeat if the condition is true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*-5-A9DLVcWj8OsMQ.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/repeatUntil.o.png">Image from rx wiki</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2b6804b9f85ecaa53dc1a18bc6fa91f/href">https://medium.com/media/b2b6804b9f85ecaa53dc1a18bc6fa91f/href</a></iframe><p>The output of this code will be the same as the repeat code above.</p><p><strong>Observable.repeatWhen</strong></p><p>The concept of this operator is quite difficult to understand at first but bear with me. First, look at the marble diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E_SWD2q3gpbURrkt.png" /><figcaption><a href="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/repeatWhen.f.png">Image from rx wiki</a></figcaption></figure><p>Based on the diagram, the operator creates an intermediate stream of onComplete events. This means that retryWhen will only react when onComplete of the input is triggered. Now, this stream of onComplete which we will be calling Observable&lt;OnComplete&gt; (in reality, it is a Observable&lt;?&gt; because retryWhen does not care about the item type) will be used as an input to a handler. Now, you can use this Observable&lt;OnComplete&gt; to decide if you want to repeat or not. The handler function should return the same Observable&lt;OnComplete&gt; for this to work. Now, the power of retryWhen lies on the range of operators you can apply to this Observable&lt;OnComplete&gt;. Let’s take an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e594ec2314c9c841d7e5de4d130df197/href">https://medium.com/media/e594ec2314c9c841d7e5de4d130df197/href</a></iframe><p>Observe the code first before running. We can see that our handler function will only take 3 onComplete events from the Observable&lt;OnComplete&gt; before terminating. Will this be true? Let’s check the output below.</p><pre>hello<br>hi<br>hello<br>hi<br>hello<br>hi<br>onComplete</pre><p>Indeed it is. You can do tons of things to this input observable like adding a constant delay to implement a polling mechanism, or a combination of both delay and numbered repeats.</p><p><strong>Observable.defer</strong></p><p>This will be the last factory operator that we will be discussing in this series.</p><p>Observable.defer serves the same purpose as fromCallable, except this one is more verbose. They both provide state information to each subscriber. Check its marble diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZVqy4baZ-PxFYaAC.png" /><figcaption><a href="http://reactivex.io/documentation/operators/defer.html">Image from rx docs</a></figcaption></figure><p>Let’s try and convert our previous fromCallable example to a defer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b03bc19ebfa7fb46481513d756fa484f/href">https://medium.com/media/b03bc19ebfa7fb46481513d756fa484f/href</a></iframe><p>We can represent it via a combination of just + defer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ab1cd744f150274aa9e46198e791eec/href">https://medium.com/media/7ab1cd744f150274aa9e46198e791eec/href</a></iframe><p>That concludes observable factories. On the next tutorial, we will discuss different types (and kinds) of observables.</p><p>Check out the other articles in this series.</p><ol><li><a href="https://medium.com/tompee/rxjava-ninja-introduction-to-reactive-programming-4b1e27b20576">Introduction to Reactive Programming</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-building-your-first-observables-and-observers-4e6c4ad9e243">Building your first Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">In Depth Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">Marble Diagrams and Operators</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">Observable Factories Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">Observable Factories Part 2</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">Single, Maybe and Completable</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">Hot and Cold Observables</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">Filtering Operators Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">Filtering Operators Part 2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e52a78be4cda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">RxJava Ninja: Observable Factories Part 2</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava Ninja: Observable Factories Part 1]]></title>
            <link>https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/98c97f6db853</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[rxjava-ninja]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[tompee]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 07:48:19 GMT</pubDate>
            <atom:updated>2018-10-01T02:08:52.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D2O7_bjlOuZ_I2a6" /><figcaption>Photo by <a href="https://unsplash.com/@spacex?utm_source=medium&amp;utm_medium=referral">SpaceX</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).</p><p>Today, we will learn about the different observable factories in RxJava2 at our disposal (finally). We already discussed Observable.create in one of the previous articles and frankly speaking, that is the most complicated one so if you think you had no problem following that, the rest should be pretty easy for you as well. Let’s start by revisiting our old friend, just.</p><blockquote>Note: The factory methods are also treated as operators since it transforms an input to an Observable. This means they can be represented with marble diagrams.</blockquote><p><strong>Observable.just</strong></p><p>Observable.just is a pretty straightforward operator. It wraps you input as an observable and returns them as items. Below is the marble diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ykWmbXzmm0rirDDb.png" /><figcaption><a href="http://reactivex.io/documentation/operators/just.html">Image from rx docs</a></figcaption></figure><p>The just operator can accept a minimum of 1 and a maximum of 10 inputs. Note that the type of inputs should be the same. Let’s see an example.</p><blockquote>Note: In other platforms, Observable.just is equivalent to Observable.Return. However in Java, methods are camel-case and return is a keyword so it was changed to just.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05507458d1a31574493d8093c475d6fd/href">https://medium.com/media/05507458d1a31574493d8093c475d6fd/href</a></iframe><p>The output of this one would be</p><pre>Person1<br>Person2<br>Person3</pre><p>One important thing that you should be aware of is that the input can contain expressions like Observable.just(10 + 1). If for some reason, an exception happened in the input expression, it will not be propagated through the onError channel because it is evaluated first before invoking just. This means you can encounter runtime exception when using just.</p><p><strong>Observable.fromIterable</strong></p><p>The Observable.fromIterable belongs to the family of from operators. The from marble diagram is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hk2c2a09SpYicrgL.png" /><figcaption><a href="http://reactivex.io/documentation/operators/from.html">Image from rx docs</a></figcaption></figure><p>As the name suggests, it accepts an iterable sequence input an emits the items in the sequence individually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e648084a60a6824be231a55f7192f819/href">https://medium.com/media/e648084a60a6824be231a55f7192f819/href</a></iframe><p>The code above will output</p><pre>Mazda<br>BMW<br>Toyota</pre><p>This operator is useful in cases wherein your input is a collection and you need to operate on each of the items individually without spreading the list explicitly.</p><p><strong>Observable.fromArray</strong></p><p>Observable.fromArray is similar to fromIterable but it accepts a variable number of arguments instead. This is what is used by just when used with more than 1 parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/284081e3f61b643c589f34688aabcd8a/href">https://medium.com/media/284081e3f61b643c589f34688aabcd8a/href</a></iframe><p>This will have the same output as fromIterable example.</p><p><strong>Observable.fromCallable</strong></p><p>Observable.fromCallable is a very powerful operator. It accepts an instance of Callable&lt;V&gt; as input. This callable will not be invoked until subscription and is therefore lazy. Also, since the call method of the Callable&lt;V&gt; is invoked during subscription, any exception encountered will be propagated through the onError channel. Let’s demonstrate both cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a4a2a60c2b07bf141e9308d7e66ddd2/href">https://medium.com/media/6a4a2a60c2b07bf141e9308d7e66ddd2/href</a></iframe><p>The code above prints the current time before and after subscribe. The output of this is</p><pre>15:27:05.182651<br>15:27:10.275867</pre><p>If this is not lazy, the time should have been resolved at the declaration of the observable and should be pretty close to each other. But since it is lazy, it was actually resolved at subscription hence the 5 seconds gap. Now let’s look at the error propagation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68bdb0c65085ae8b3d6cab0e6d419d1b/href">https://medium.com/media/68bdb0c65085ae8b3d6cab0e6d419d1b/href</a></iframe><p>This will output</p><pre>onError: Forced error</pre><p>which is expected since all exceptions will propagate in the onError channel.</p><p>This operator is also a part of the <em>Start</em> family. The start family emits the return value of a function as an item. The marble diagram of the start family is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zJSLOnQm7C5B-aBA.png" /><figcaption><a href="http://reactivex.io/documentation/operators/start.html">Image from rx docs</a></figcaption></figure><p><strong>Observable.fromFuture</strong></p><p>Unfortunately, this observable did not travel through time to get included in RxJava’s list of operators. This is a converter for Future types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d678ebf5ff09f68428645a42cb03457/href">https://medium.com/media/7d678ebf5ff09f68428645a42cb03457/href</a></iframe><p>This will output the message below (which is confusing because we already established that it is not from the future).</p><pre>I am from the future</pre><p><strong>Observable.fromPublisher</strong></p><p>This operator serves the same purpose as Observable.create but is readily compatible with Reactive-Streams’ Publisher type. It is generally used for potentially unbounded sequences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7adae9e123578173c9ad476ca0918fc2/href">https://medium.com/media/7adae9e123578173c9ad476ca0918fc2/href</a></iframe><p>This will output an infinite sequence of I am infinite strings.</p><p>That concludes the family of <em>from</em> operators. Let us now discuss a very “limited” family of operators. They do not offer much aside from testing or combination with other observables. We will not demonstrate their behavior anymore. I leave it up to you to check them for yourselves.</p><p><strong>Observable.Empty</strong></p><p>This operator does not emit anything and will go straight to sending the complete notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XJ_hEm33tqn8Mc6x.png" /><figcaption><a href="http://reactivex.io/documentation/operators/empty-never-throw.html">Image from rx docs</a></figcaption></figure><p><strong>Observable.Never</strong></p><p>This operator never emits anything, not even the complete notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cqDCME5fJiM7T7-g.png" /><figcaption><a href="http://reactivex.io/documentation/operators/empty-never-throw.html">Image from rx docs</a></figcaption></figure><p><strong>Observable.error</strong></p><p>This operator does not emit anything and sends an error notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*ppKhuJjyIefe4VUBq3qNig.png" /><figcaption><a href="http://reactivex.io/documentation/operators/empty-never-throw.html">Image from rx docs</a></figcaption></figure><p><strong>Observable.Range</strong></p><p>This operator emits a sequence of integers starting from start and until count is reached. If integer is not enough, there is a variant that emits long named rangeLong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZzUf3ql5H8FJqpNt.png" /><figcaption><a href="http://reactivex.io/documentation/operators/range.html">Image from rx docs</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e79f384424984c7b2caec5c31e46f494/href">https://medium.com/media/e79f384424984c7b2caec5c31e46f494/href</a></iframe><p>The above code will output</p><pre>0<br>1<br>2<br>3<br>4</pre><p>Be careful not to interpret the second parameter as the final item value. This operator is useful for indexing or as an alternative and reactive approach to for loops. There is another variant of range that is time based and we will discuss that in the next part since it has some interesting properties.</p><p>This should be enough for the Part 1. On the next article, we will discuss more operators that creates observables.</p><p>Check out the other articles in this series.</p><ol><li><a href="https://medium.com/tompee/rxjava-ninja-introduction-to-reactive-programming-4b1e27b20576">Introduction to Reactive Programming</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-building-your-first-observables-and-observers-4e6c4ad9e243">Building your first Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">In Depth Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">Marble Diagrams and Operators</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">Observable Factories Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">Observable Factories Part 2</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">Single, Maybe and Completable</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">Hot and Cold Observables</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">Filtering Operators Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">Filtering Operators Part 2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c97f6db853" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">RxJava Ninja: Observable Factories Part 1</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava Ninja: Marble Diagrams and Operators]]></title>
            <link>https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/d5ea45a3c1e0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[rxjava-ninja]]></category>
            <category><![CDATA[tompee]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Tue, 31 Jul 2018 08:30:31 GMT</pubDate>
            <atom:updated>2018-10-01T02:08:42.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QsbivY8UJk2oKtka" /><figcaption>“Blue sparks and flames over a piece of metal with a welder leaning over it” by <a href="https://unsplash.com/@roblambertjr?utm_source=medium&amp;utm_medium=referral">Rob Lambert</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).</p><p>Before we go to where the action in RxJava truly is, let us familiarize ourselves with the concept of <strong>Operators </strong>and <strong>Marble Diagrams</strong>.</p><p><strong>Operators</strong></p><p>Operators accepts input, manipulates it, and produces an output. Most RxJava operators work with observables on one or both ends so they must be pretty special. Why you ask? Because we know that observables communicate via notifications. This means that if an operator wishes to manipulate the items, it must follow this notification mechanism as well. To demonstrate this, let us look at an example operator, the map operator.</p><p>map transforms an input. The transformation may involve a change in value or type. Calling the map operator will instantiate a ObservableMap&lt;T, R&gt; class. If we check at the ObservableMap&lt;T, R&gt; code, we can see that it inherits AbstractObservableWithUpstream&lt;T, U&gt; which in turn extends Observable&lt;U&gt;. This means that the map operator is also an observable. Since it is an observable, it should implement subscribeActual. The subscribeActual of ObservableMap&lt;T, U&gt; creates an instance of MapObserver&lt;T, U&gt; and subscribe on the original source. The MapObserver&lt;T, U&gt; onNext method transforms the source item based on the transformation function before sending it to the subscriber of ObservableMap&lt;T, U&gt;.</p><p>Based on the above observation, we can conclude the following about observable operators.</p><ol><li>Operators, when chained to an observable will act as the latter’s immediate “observer”.</li><li>This intermediate observer will operate on each item, not on the entire observable (vertical processing).</li><li>Since chaining creates a unique process pipeline, order of operations matter.</li><li>Operators do not trigger runtime (only subscribe does).</li><li>Operators are also observables that can be subscribed upon.</li></ol><p>Note that these conclusions hold true, unless otherwise proven incorrect in subsequent articles.</p><p>We will define two important terminology here.</p><ul><li>Upstream — The up side of the processing pipeline from an operator’s point of view.</li><li>Downstream — The down side of the processing pipeline from an operator’s point of view.</li></ul><p><strong>Marble Diagrams</strong></p><p>Marble diagrams are good visual representations of what happens to an input when passed through an operation. Below is the general structure of a marble diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*5D3c8i8qWGqIh6FQ.png" /><figcaption><a href="http://rxwiki.wikidot.com/marble-diagrams">Image from Rx Wiki</a></figcaption></figure><p>The x-axis represents time while the y-axis is a layer with inputs on top, operations on the middle and outputs on the bottom. The different circular points on the input is an item, the triangular icons are processed items. If an error occurred, it will be denoted with <strong>x</strong> and a complete event with <strong>|</strong>. Let’s see what a map marble diagram looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*N_uN5hta1ntt_MW2zigExQ.png" /><figcaption><a href="http://reactivex.io/documentation/operators/map.html">Image from rx docs</a></figcaption></figure><p>The line on top is our input observable. It emits 1, 2 and 3 before completing. On the middle layer we have a map operator that transforms the input value by multiplying it with a factor of 10. The bottom line is the output containing the result of the operation which is 10, 20 and 30. Sounds about right.</p><p>On the succeeding articles we will show some marble diagrams alongside the operators for easier visual understanding.</p><p>Now that we have been introduced with the concept of operators and marble diagrams, there is nothing holding us back from learning the actual factories and operators in RxJava. Stay tuned.</p><p>Check out the other articles in this series.</p><ol><li><a href="https://medium.com/tompee/rxjava-ninja-introduction-to-reactive-programming-4b1e27b20576">Introduction to Reactive Programming</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-building-your-first-observables-and-observers-4e6c4ad9e243">Building your first Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">In Depth Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">Marble Diagrams and Operators</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">Observable Factories Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">Observable Factories Part 2</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">Single, Maybe and Completable</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">Hot and Cold Observables</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">Filtering Operators Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">Filtering Operators Part 2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ea45a3c1e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">RxJava Ninja: Marble Diagrams and Operators</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava Ninja: In Depth Observables and Observers]]></title>
            <link>https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19?source=rss----be2594f1cff8---4</link>
            <guid isPermaLink="false">https://medium.com/p/4c0ebdb5ff19</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava-ninja]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[tompee]]></category>
            <dc:creator><![CDATA[Tompee Balauag]]></dc:creator>
            <pubDate>Tue, 31 Jul 2018 03:32:18 GMT</pubDate>
            <atom:updated>2018-10-01T02:08:32.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xLoKAY2ZUhZpEq9l" /><figcaption>Photo by <a href="https://unsplash.com/@designedbyjess?utm_source=medium&amp;utm_medium=referral">Jess Watters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a part of the RxJava Ninja series. The complete list of the articles for this series can be found at the end of this article (and will be updated as more articles become available).</p><p>In the last article, we created our first observable and observer. Today we will talk a little more about them and investigate how they uphold the observable contract.</p><p><strong>Observable, a closer look</strong></p><p>As we learned from the previous article, the observable communicates with the observer by means of notifications. The observer defines 4 notifications the observable can use to signal and event or emit an item. For the benefit of those who have not seen the previous article, below is the definition of the Observer&lt;T&gt; interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50591ecf0a977ec86536d63c44d3e584/href">https://medium.com/media/50591ecf0a977ec86536d63c44d3e584/href</a></iframe><p>Before we investigate the above notifications, let me introduce you to a very powerful observable factory method, Observable.create.</p><p>The Observable.create method allows you to create your own custom observable. It accepts an instance of ObservableOnSubscribe&lt;T&gt; which is a single abstract method (SAM) defined as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bddc1acbf4246a1be093e01893d535ea/href">https://medium.com/media/bddc1acbf4246a1be093e01893d535ea/href</a></iframe><p>The subscribe method requires an instance of the ObservableEmitter&lt;T&gt; class. This ObservableEmitter is an abstraction of the Observer class with added methods since it also serves as the <strong>source</strong> of items. The moment the observer subscribes to your observable, it will invoke this subscribe method and your custom emitter code will run. Let’s see it in action. Consider this example.</p><blockquote>Note: It is highly recommended to target Java 8. This is because lambda expressions can greatly reduce boilerplate code. In the succeeding examples, SAM instances will be expressed in lambda instead of anonymous classes.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db9f52c2ac4174ad1cf8ebc0789649e1/href">https://medium.com/media/db9f52c2ac4174ad1cf8ebc0789649e1/href</a></iframe><p>This code creates an observable of type String that when subscribed upon will emit three strings and an onComplete. As I said, this is a very powerful factory method as it allows you to create an observable from virtually anything you can think of. Running this will not do anything, for reasons discussed in the previous article. Attaching an observer that logs each method will output this.</p><pre>onSubscribe<br>onNext: First item<br>onNext: Second item<br>onNext: Third item<br>onComplete</pre><p><strong>The exact order of our items are preserved</strong>, because the observable contract enforces so.</p><p>Now that we know how to create an observable, let’s validate some of the behaviors defined in the observable contract. For the succeeding examples, assume that all observables are subscribed upon.</p><p>We already proved sequence preservation, next on our list is an observable that does nothing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e605d9a0b57f3650d77391c024b0356/href">https://medium.com/media/6e605d9a0b57f3650d77391c024b0356/href</a></iframe><p>This will output</p><pre>onSubscribe</pre><p>No crashes, compile errors or anything. Therefore <strong>it is perfectly valid for an observable to emit nothing</strong>.</p><p>Next, we will investigate onError. The onError method requires a Throwable parameter that is annotated as NonNull. Therefore, <strong>the observable must always provide the cause of the error</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48fbe88f675955e277547d7322a94c6d/href">https://medium.com/media/48fbe88f675955e277547d7322a94c6d/href</a></iframe><p>The output of this code is as follows.</p><pre>onSubscribe<br>onError</pre><p>Therefore, <strong>when </strong><strong>onError is sent, any succeeding calls to </strong><strong>onNext or </strong><strong>onComplete does nothing</strong>.</p><p>Last thing that we will check is onComplete. For the rest of the assumptions, I invite you to validate them on your own as it will be a good exercise for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e96996e2611c552626ac265e4ee3f4c4/href">https://medium.com/media/e96996e2611c552626ac265e4ee3f4c4/href</a></iframe><p>This will actually result to a runtime error. This is compliant because <strong>when an </strong><strong>onCompleted or </strong><strong>onError is already sent, the observable should not send any more notifications</strong>. It is more lenient with onNext, but it will throw runtime exception on onError.</p><p>Now that we proved a great deal about observables, let’s turn our attention to observers.</p><p><strong>Observer, a closer look</strong></p><p>Let’s see what happens the moment an observer subscribe to an observable. As we have seen before, the ObservableSource&lt;T&gt; has a subscribe method that looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a287147f5cca0e70707430cafee8cd0/href">https://medium.com/media/6a287147f5cca0e70707430cafee8cd0/href</a></iframe><p>When subscribing to an observable, you need to pass an instance of your observer. Let’s see what happens in the context of Observable.create.</p><p>When you use the Observable.create method, you are actually instantiating a ObservableCreate&lt;T&gt; class, a subtype of Observable&lt;T&gt;. Observable&lt;T&gt; has an abstract method called subscribeActual that all concrete subtypes should implement. This method is what is being called when the subscription actually happens. But before it calls the subscribeActual methods, all registered subscribe hooks will be invoked first. This phase is <strong>Subscription Time. </strong>The subscribeActual method of ObservableCreate&lt;T&gt; is defined as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b86f632d237b55edb4051480eb2a9b/href">https://medium.com/media/31b86f632d237b55edb4051480eb2a9b/href</a></iframe><p>It will create an emitter instance using the passed observer (remember, emitters are abstractions of observer) and calls the onSubscribe. This is why onSubscribe is always printed out at the beginning because it is the first method to be invoked. Only then the subscribe method of the ObservableOnSubscribe&lt;T&gt; is called where everything happens. This is <strong>Runtime</strong>.</p><p>If you notice, we keep on taking the Disposable argument of the onSubscribe for granted. But today, we will no longer do that.</p><p>The Disposable interface is defined as such.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d1abec95e5a51012a527a1f434b28b/href">https://medium.com/media/32d1abec95e5a51012a527a1f434b28b/href</a></iframe><p>If you are to take a guess, what do you think it does? Well, it disposes something, that I am sure. But dispose what? Let’s check again at the context of Observable.create.</p><p>In the subscribeActual, we can see that the disposable instance passed is the instance of the CreateEmitter&lt;T&gt; class. Let’s see how it is defined.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e524bc7c13b94bcff72d2e2f7e50f1d/href">https://medium.com/media/4e524bc7c13b94bcff72d2e2f7e50f1d/href</a></iframe><p>Sounds good. Nothing special. Your observer will receive an instance of this but in the form of a Disposable. What happens when we dispose this? According to the source, it sets some flag to disposed but does so in an atomic fashion to prevent race conditions. So what if a flag is set to disposed? How does that affect my observable? The answer lies in the onNext implementation of the CreateEmitter&lt;T&gt; class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a33a02d6550aa876aa41db6aaf31714/href">https://medium.com/media/0a33a02d6550aa876aa41db6aaf31714/href</a></iframe><p>When the emitter is disposed, it will skip emitting succeeding items. We get it now. This is the <strong>unsubscribe</strong> mechanism. This disposable is actually called the <strong>subscription</strong>. <em>You can unsubscribe from an observable by disposing the subscription</em>.</p><p>We just witnessed how observer subscription and unsubscription works. Note that we observed it in the context of the Observable.create method but the principle is the same for all other types of Observable. If you have doubts, I invite you to check the source code of other factory methods.</p><p><strong>Reducing Observer boilerplate code</strong></p><p>In case you haven’t noticed, an Observer instance requires you to implement 4 abstract methods. This involves a lot of boilerplate code. Fortunately, Observable&lt;T&gt; provides a lot of subscribe overloads depending on your preference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a94a50856d6313a9d230a7bc744b98a7/href">https://medium.com/media/a94a50856d6313a9d230a7bc744b98a7/href</a></iframe><p>The above code shows a variant of the subscribe method accepting an instance of the Consumer&lt;T&gt; class. This single consumer input defines the behavior when onNext is called. This is useful for cases wherein you are sure that your observable will not output an error and you can safely ignore the onComplete event. Be wary though that when an error occurred and no onError handler is specified, you will encounter a runtime exception. So in production, it is always advisable to implement onError.</p><p>On variants wherein Observer&lt;T&gt; is not required, the Disposable object will be returned instead.</p><p>With lambda expressions, method references and chaining, boilerplate code can be further reduced. An example can be seen below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c74e16c56af3529652e05c570e54e1/href">https://medium.com/media/35c74e16c56af3529652e05c570e54e1/href</a></iframe><p><strong>Bonus: Execution context</strong></p><p>We will just briefly tackle execution context for now as it will be discussed in detail in the future. Consider this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83ddf7eaf4099a336d972bde1c202977/href">https://medium.com/media/83ddf7eaf4099a336d972bde1c202977/href</a></iframe><p>This method will log the different execution context in different phases. This will output</p><pre>Assembly execution context: main<br>Subscription execution context: main<br>Runtime execution context: main</pre><p>We can conclude therefore that by default, subscription is synchronous and runs on the same thread as the Assembly. Let’s see if this conclusion holds true without exceptions in the future articles.</p><p>Check out the other articles in this series.</p><ol><li><a href="https://medium.com/tompee/rxjava-ninja-introduction-to-reactive-programming-4b1e27b20576">Introduction to Reactive Programming</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-building-your-first-observables-and-observers-4e6c4ad9e243">Building your first Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">In Depth Observables and Observers</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-marble-diagrams-and-operators-d5ea45a3c1e0">Marble Diagrams and Operators</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-1-98c97f6db853">Observable Factories Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-observable-factories-part-2-e52a78be4cda">Observable Factories Part 2</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-single-maybe-and-completable-b5907dddc5e4">Single, Maybe and Completable</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-hot-and-cold-observables-19b30d6cc2fa">Hot and Cold Observables</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-1-e7e72b39d70">Filtering Operators Part 1</a></li><li><a href="https://medium.com/tompee/rxjava-ninja-filtering-operators-part-2-e4a3046646c6">Filtering Operators Part 2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0ebdb5ff19" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tompee/rxjava-ninja-in-depth-observables-and-observers-4c0ebdb5ff19">RxJava Ninja: In Depth Observables and Observers</a> was originally published in <a href="https://medium.com/tompee">Familiar Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>