Hot and cold rx-java Observable

My own understanding of Hot and Cold Observable is quite shaky, but here is what I have understood till now!

Cold Observable

Consider an API which returns an rx-java Observable :

Now, the first thing to note is that the typical Observable does not do anything until it is subscribed to:

So essentially if I were to do this:

Nothing would be printed or returned, unless there is a subscription on the Observable this way:

So now, what happens if there are multiple subscriptions on this Observable:

With a cold observable the code would get called once more and the items emitted again, I get this on my machine:

Hot Observable – using ConnectableObservable

Hot Observable on the other hand does not really need a subscription to start emitting items. A way to implement a Hot Observable is using aConnectableObservable , which is a Observable which does not emit items until its connect method is called, however once it starts emitting items, any subscriber to it gets items only from the point of subscription. So again revisiting the previous example, but with a ConnectableObservable instead:

and the following gets printed:

Hot Observable – using Subject

Another way to convert a cold Observable to a hot one is to use a Subject . Subjects behave both as an Observable and an Observer, there are different types of Subjects available with different behavior. Here I am using a Subject called aPublishSubject which has a Pub/Sub behavior – the items get emitted to all the subscribers listening on it. So with a PublishSubject introduced the code looks like this:

See how the PublishSubject is introduced as a subscriber to the Observable and the other subscribers subscribe to the PublishSubject instead. The output will be similar to the one from ConnectableObservable.

This is essentially it, the extent of my understanding of Hot Observable. So to conclude, the difference between a Cold and a Hot Observable is about when the subscribers get the emitted items and when the items are emitted – with a Cold Observable they are emitted when they are subscribed to and typically get all the emitted items, with a Hot Observable the items are emitted without a Subscriber and subscribers get items emitted after the point of subscription typically.



2. Excellent javadoc on rx-java –

Intent Resolving in Android M

Warning! Resolving of “Implicit Intent”s in Android Marshmallow is not working as the same as before. This may break your app’s behavior.
提醒大家注意!Implicit Intent(隐式意图)在Android M中的解决方式并不像以前那样。
Let me explain the expected behavior and why is not working:
I have recently been working on a small open source project called “Open Link With”. It will hopefully be in the Play Store soon.
我最近一直在从事于开源项目“Open Link With”的工作。这个项目有希望很快在Play Store上线。
My app gives you the ability to switch between other apps. When you share a link with me, I basically grab the link and query all the Activity’s that can handle that link. And finally I mimic the system dialog and let you switch apps.
I was using the below method as always:

It is a familiar method to almost all Android developers and I am sure that it is currently being used in lots of apps.
I have 2 browsers in my phone. “An Intent with Google+ URL” is expected to give a list of 3 ResolveInfo objects (Google+ app and 2 browsers).
在我的手机上有2个浏览器。“An Intent with Google+ URL”(一个包含了Google+ URL的意图)应该预期地给出一个list其中包含三个ResolveInfo实体。

Well, not anymore!

Welcome to Android Marshmallow!


欢迎来到Android M !

Android Marshmallow introduced App Links. The system basically authenticates with your web-page and opens those URLs automatically using your application without asking anything to user. Or you can go to system Settings, Apps, click an app, click “Open by default” and then set “Open in this app” to use always that app.

Android M引入了App Links这一概念。


或者你可以去系统设置里的Apps选项,点击一个应用,点击”Open by default”,或是设置

“Open in this app”从而总是用这个应用打开。

In that case, queryIntentActivities method will give developers a list with only1 Activity (which is Google+ in this case).


Even if this is the desired behavior, this should be documented because it breaks the behavior of a public API.


I researched a little bit and found MATCH_ALL flag. It’s documentation says that it will disable all system level filters.


It didn’t do anything for me. I opened the source code (at least we have that!) and investigated the method.


It looks like they prioritize the domain verified applications. They did not just prioritize in their internal system, they also did it in the public API.



If there is a domain verified application, it does not return anything else.MATCH_ALL flag removes some system filters but only if there is no verified application.

如果有一个domain verified application,它并不返回任何应用。

MATCH_ALL这个flag移除了一些系统的过滤,但是只是在没有verified application的情况下。

I couldn’t find any way to workaround this behavior. It simply eliminates browser apps even when their IntentFilters match.


There is no workaround because it is an internal component (which we cannot access) and Android SDK communicates with it using IPC communication using AIDL.

这个是并没有补救措施是因为它是一个内部的组件(我们不能访问)并且Android SDK


Most of the developers are using this method to find if there is at least 1 Activity to handle the implicit Intent. In most of the situations the first item in the list is the one you want anyway.



After spending hours to understand what’s going on and trying to find a workaround, I thought everyone should know this.


There are lots of behavior changes in Android M. Google actually provided a list of behavior changes. You can find it here. I am sure that just like this, there are lots of hidden behavior changes that may break applications.

在Android M中有很多操作行为的改变。谷歌实际上提供了一系列操作。你可以在这里看到。就像本文中这样的,很多隐藏的操作改变会打破应用的行为。

So beware of this, and check your situation if you use PackageManagermethods.


Thanks to the people who proofread this article: Yağmur DalmanSebastiano PoggiSalim KAYABAŞIHasan Keklik


Yağmur DalmanSebastiano PoggiSalim KAYABAŞIHasan Keklik

@tasomaniac and +SaidTahsinDane关注我

Follow me on @tasomaniac and +SaidTahsinDane

Getting Started with RxJava and Android

What is ReactiveX?
ReactiveX is an API that focuses on asynchronous composition and manipulation of observable streams of data or events by using a combination of the Observer pattern, Iterator pattern, and features of Functional Programming.
 Handling real-time data is a common occurrence, and having an efficient, clean, and extensible approach to handling these scenarios is important. Using Observables and operators to manipulate them, ReactiveX offers a composable and flexible API to create and act on streams of data while simplifying the normal concerns of asynchronous programming like thread creation and concurrency issues.
处理实时数据经常发生,并且用一种高效的,简洁的,可拓展的方法去处理这些情况是非常重要的。使用Observables 和operators 去操作它们,ReactiveX 提供了一种可组合的,灵活的API去创建,执行数据流,这样就使普通的异步编程问题像线程创建和并发问题一样简单。

Intro to RxJava

RxJava is the open-source implementation of ReactiveX in Java. The two main classes are Observable and Subscriber. In RxJava, an Observable is a class that emits a stream of data or events, and a Subscriber is a class that acts upon the emitted items. 
RxJava是用Java语言编写的开源的ReactiveX实现。两个主要的类是Observable 和Subscriber。在RxJava,Observable 是一个它发出数据流和事件的类,而Subscriber 是一个根据发出的Item进行操作的类。
The standard flow of an Observable is to emit one or more items, and then complete successfully or with an error. An Observable can have multiple Subscribers, and for each item emitted by the Observable, the item will be sent to the Subscriber.onNext() method to be handled. Once an Observable has finished emitting items, it will call the Subscriber.onCompleted() method, or if there is an error the Observable will call the Subscriber.onError() method.
一个Observable的标准流是用于发出一个或者更多的Item,然后成功完成或者出错。一个Observable 可以拥有多个Subscriber,并且对于每个Observable 发出的Item都会被送到各自的Subscriber的onNext()方法去处理。一旦一个Observable 发送完毕一些Item,它会调用Subscriber.onCompleted() 方法,或者出错后调用Subscriber.onError()方法。
 Now that we know enough about the Observable and Subscriber class, we can continue on to an introduction on creating and subscribing to Observables.
现在我们已经对Observable 和Subscriber类了解得足够多了,我们可以继续进行如何创建并且订阅一个Observable的介绍了。

This Observable emits the integers 1, 2, and 3 and then completes. Now we need to create a Subscriber so we can act upon the stream of emissions.
这个Observable 发送了integer对象1,2,3然后发送完毕。现在我们需要创建一个Subscriber ,这样我们就能依据流的排放操作了。

Our Subscriber will simply print out any items emitted and notify us upon completion. Once you have an Observable and a Subscriber you can connect them with the Observable.subscribe() method.
Subscriber 会打印出所有的被发出的item并且提示我们已经发送完毕。你可以用Observable.subscribe()方法把Observable 和Subscriber 关联在一起。

Operators 操作符

Creating and subscribing to an Observable is simple enough, and may not seem overly useful, but that is just the beginning of what is possible with RxJava. Any Observable can have its output transformed by what is called an Operator, and multiple Operators can be chained onto Observable. For example, in our previous Observable, say we only wanted to emit odd numbers that we receive. To accomplish this, we can use the filter() operator.
创建并且订阅一个Observable 真心简单,似乎并不是很有用,但是这只是RxJava可能处理的开始。任何Observable 都可以用Operator转化为自己的输出形式,多个Operators 可以受缚于Observable。例如,在我们前面的Observable,我们只想接收发送的奇数时,我们可以用filter() operator.

Our filter() operator defines a function that will take in our emitted Integer values, and return true for all odd numbers, and false for all even numbers. The values that return false from our filter() function are not emitted to the Subscriber, and we will not see them in the output.
我们的filter() operator(过滤函数 操作符)定义了一个函数,这个函数将会接收发送出的数值,并且当时奇数的时候返回true,偶数的时候返回false。从filter()函数返回false时的数值不会发送给Subscriber,我们也不会在输出结果中看见它们。
Notice that the filter() operator returns an Observable that we then subscribe to like we did before. Now say that I want to find the square root of the emitted odd numbers. One way of doing this would be to calculate the square root in each of the onNext() calls of our Subscriber. However, this is desired as it would not be possible to further transform the data stream if we are doing the square root calculations in our Subscriber. To accomplish this we can chain the map() operator with the filter() operator.
需要注意的是filter() operator像我们过去做的那样返回一个我们订阅的Observable 。现在我们像发现奇数的平方根,一种方法是在Subscriber的onNext() 被调用时计算每个值的平方根。然而,这被作为一种不能长远转换数据流的方法。为了解决这个问题,我们引入map()操作符和filter()操作符相配合。

Chaining operators is an integral part to RxJava and gives you the flexibility to accomplish anything you need. With an understanding of how Observables and Operators interact we can move onto the next topic: integrating RxJava with Android.
当我们理解了Observables和 Operators关系之后,就可以看下一话题了:整合RxJava和Android。

Simple Threading in Android

A common scenario in Android development is the need to offload some amount of work to a background thread, and once that task has finished, post the results on the main thread in order to display the results.
With Android, we are given multiple options to do something like this natively, using AsyncTasks, Loaders, Services, etc. However, these solutions are often not the best. Asynctasks can easily lead to memory leaks, CursorLoaders with a ContentProvider require a large amount of configuration and boilerplate code to setup, and Services are intended for longer running background tasks and not fast-finishing operations such as making a network call or loading content from a database.
Android自然给了我们多种选择去做这样的东西,例如,用AsyncTasks, Loaders, Services,等等。然而,这些解决方案通常不是最好的。Asynctasks 很容易导致内存的泄露,ContentProvider 提供的CursorLoaders 需要一大堆配置代码和模板代码,Services预期用于更长时间在后台运行的任务并且不是很快就完成的操作,像建立一个网络呼叫或者是从数据库加载内容。
Let’s see how RxJava can help solve these problems. Given the following Layout that has a button to start a long running operation, and an always displayed progress circle so that we can make sure that our operation is being run on a background thread, and not on the main UI thread.

Once the button is clicked, it will disable the button and start the operation, and once the operation is completed a Snackbar will be displayed and the button re-enabled. Here is the sample AsyncTask, and our “long running operation”. The onClick for the button simply creates a new SampleAsyncTask and executes it.
一旦按钮被点击,按钮将会被禁用并且开启一个操作,一旦操作被完成一个Snackbar将会显示并且按钮被重新设置可用。这是AsyncTask的例子和我们的长期操作。按钮的onClick 事件创建了一个新的SampleAsync Task 并且执行它。

Now how would we convert this AsyncTask to use RxJava? First, we need to add the following to our app’s gradle build file: compile ‘io.reactivex:rxjava:1.0.14’. Then we would need to create an Observable that calls our long running operation. This can be done using the Observable.create() method.
现在我们如何将AsyncTask 替换成RxJava呢?第一步,我们需要在gradle build 中添加:compile ‘io.reactivex:rxjava:1.0.14’.,然后,我们需要创建一个Observable 去调用long running operation,可以用Observable.create()方法。

Our created Observable will call the longRunningOperation and post the result to onNext(), and then call onCompleted() to complete the Observable (NOTE: our operation is not called until we subscribe to our Observable). Next, we need to subscribe to our Observable when our button is clicked. I’ve added a new button that will handle the RxJava version of our task.

我们创建的Observable 将会调用longRunningOperation 并将结果传递给onNext(),然后调用onCompleted()完成Observable(注意:我们的操作并没有被调用直到我们订阅了Observable)。接下来,当按钮被点击时,我们需要订阅Observable 。我已经添加了一个新的按钮,用以处理RxJava 版本的任务。

Now when we build our application and click the new button, what happens? Our progress indicator freezes, and our UI becomes unresponsive. This is because we have not defined what thread we should observe our Observable on and what thread we should subscribe to it on.
现在我们build 了APP之后,点击新的按钮,将会发生什么?我们的进度条指示器冻结了,我们的UI变得迟钝。这是因为我们还没有定义应该观察Observable的线程和应该订阅它的线程。
This is the function of RxJava’s Schedulers. With any Observable you can define two different threads that the Observable will be operated upon. Using Observable.observeOn() can define a thread that is used to monitor and check for newly emitted items from the Observable (the Subscriber’s onNext, onCompleted, and onError methods execute on the observeOn() thread), and using Observable.subscribeOn() can define a thread that will run our Observable’s code (the long running operation).
这是RxJava的Scheduler(调度器)的作用。任何Observable 你都可以定义2种不同的对其进行操作的线程。用Observable.observeOn()可以定义一个线程用于监视并检查Observable发出的新的Item( Subscriber的 onNext, onCompleted, and onError 方法在observeOn()所在的线程执行),并且用Observable.subscribeOn()可以定义一个线程执行Observable中的代码(the long running operation)
RxJava is single-threaded by default, and you will need to make use of the observeOn() and subscribeOn() methods to bring multi-threading to your application. RxJava comes with several out-of-the-box Schedulers to use with Observables, such as (for blocking I/O operations), Schedulers.computation() (computational work), and Schedulers.newThread() (creates new thread for the work). However, from an Android perspective, you might be wondering how to schedule code to execute on the main UI Thread. We can achieve this using the RxAndroid library.
RxJava 是默认单线程的,你需要使用observeOn()和subscribeOn()方法把多线程带入你的APP.
RxJava 提供一些即时可用的Scheduler配合Observable一起使用,像 (用于阻塞IO操作),Schedulers.computation()(计算量的操作),Schedulers.newThread()(新建一个线程工作)。当然,从Android代码的视角,你也许会怀疑schedule的代码是如何在主线程执行的。我们可以用RxAndroid library实现。

Preventing Leaks 避免内存泄露

One of the downsides previously mentioned with AsyncTasks is the ability to leak references to their enclosing Activity/Fragment if proper care is not taken. Unfortunately, using RxJava will not magically alleviate memory leak woes, but preventing them is fairly simple. If you’ve been following along in the code, you may have noticed that when you call Observable.subscribe() a Subscription object is returned. The Subscription class only has two methods, unsubscribe() and isUnsubscribed(). To prevent a possible memory leak, in your Activity/Fragment’s onDestroy, check Subscription.isUnsubscribed() for if your Subscription is unsubscribed, and if not call Subscription.unsubscribe(). Unsubscribing will stop notifications of items to your Subscriber and will allow the garbage collection of all related objects, preventing any RxJava related memory leaks. If you are dealing with multiple Observables and Subscribers, all Subscription objects can be added to a CompositeSubscription and all unsubscribed at the same time using CompositeSubscription.unsubscribe().

Closing Comments

RxJava provides a great alternative to the multi-threading options in the Android ecosystem. Being able to easily offload an operation to a background thread, and then publish the results on the UI Thread is a much needed feature for any Android application, and being able to apply RxJava’s multitude of operators to the results of any operation only creates more added value. While RxJava requires a good understanding of the library to fully take advantage of its features, time spent in working with the library is greatly rewarded. Further topics of RxJava that were not covered in this blog include: hot vs cold Observables, dealing with backpressure, Rx’s Subject class. The sample code for converting an AsyncTask using RxJava can be found on github.

Bonus: Retrolambda

Java 8 introduced Lambdas Expressions, unfortunately Android does not support Java 8, so we are not able to take advantage of this with RxJava. Luckily there is a library called Retrolambda which backports lambdas to previous versions of Java. There is also a gradle plugin for Retrolambda that will allow the use of lambdas in an Android application. With lambdas, the example Observable and Subscriber can be reduced to the following.

Lambdas cut down on the boilerplate code for RxJava a lot, and I would highly recommend you checkout Retrolambda for that purpose. It is usable with more than RxJava as well (notice the setOnClickListener call also makes use of Retrolambda).



Fragment transitions with shared elements

One of the cornerstones of Material design is meaningful motion between screens. Lollipop introduced support for these animations in the form of the transitions framework, which allows us to animate transitions between Activities and Fragments. I haven’t seen many articles on how to use transitions with Fragments, so I set out to write one!
切屏时有意义的运动是Material design最重要的部分之一。Android L引入了一系列过渡动画框架作为支持,这些框架让我们可以在Activity和Fragment切换之间过渡得更加生动。我并没有看到多少介绍如何使用Fragment过渡动画的文章,所以我打算着手写下本文。
Our end product is fairly simple. We will be making an app that has a grid of images, and when you click on an image the app will show a details screen. Thanks to the transitions framework, the image from the grid will animate into place on the details screen.
If you want to head straight to the sample app, you can find it here on GitHub.
What about older versions of Android?

I have good news and bad news. The bad news is that content transitions don’t exist prior to Lollipop. However, the support library provides methods that you can use to gracefully support transitions on API 21+ without littering your code with API version checks.

This article will use these support library functions to provide content transitions.

我有好消息和坏消息。坏消息就是在Android L之前并不存在内容转换。

然而,支持库提供的方法可以让你在API 21+优雅的运行,而不用为你的代码做版本的检查。这篇文章将会用到这些支持库函数做内容转换。


Unlike Activity transitions, you do not needWindow.FEATURE_ACTIVITY_TRANSITIONS to use Fragment transitions. You also don’t need Window.FEATURE_CONTENT_TRANSITIONS. As a matter of fact, you don’t need to do anything special- you should already be ready to go!

Transition Names

The framework needs a way to associate Views on the first screen to their counterparts on the second screen. Lollipop also introduced a new “transition name” property on Views that is the key to making this association.

There are two ways to add a transition name to your Views:

  • In code you can use ViewCompat.setTransitionName()Of course, you can also just call setTransitionName() on devices running Lollipop and up.
  • In your layout XML, you can use the android:transitionName attribute.

One important item to note is that within a given layout (e.g. all views in screen one), transition names must be unique. Keep this in mind when you are transitioning from a ListView or RecyclerView; defining a transition name in your row XML will lead to each row having the same transition name.

这个框架需要将第一屏中的Views和第二屏中的副本相关联。Android  L还提供了一个新的转换属性在Views,这就是关联的关键所在。有两种方法为你的Views添加转换名称:

1)在代码中使用ViewCompat.setTransitionName().当然你也可以在Android L或后续版本上的设备调用setTransitionName()


需要指出的灰常重要的一点是对于一个指定的布局(比如页面一上所有的View),transition names必须是唯一的。

当你试图做ListView或是RecyclerView的时候要牢记这一点,在你的XML的一行定义了transition name将会导致每一行都有相同的transition name.

Set up the FragmentTransaction

Setting up your FragmentTransactions should look very familiar:

The new step is calling addSharedElement() to specify what Views to share between the Fragments.


The View passed to addSharedElement() is the View in the first Fragment you want to “share” with the second Fragment. The transition name here is the transition name of the “shared” View in the second Fragment. If the View in the first screen has the transition name “foo” and the View in the second screen has the transition name “bar,” then your want to pass in “bar”.

这个通过addSharedElement()传递的View是在第一个Fragment中你想要“分享”到第二个Fragment中的那个View。这里的transition name是第二个Fragment中“分享之后”的View的transition names属性

。如果第一个页面View的transition names属性是foo,第二个页面View的transition names属性是bar,那你需要的属性是bar.

Specifying the transition animations

Finally we need to specify how we want to animate the transition between Fragments.


For the shared element:

对于shared element:

setSharedElementEnterTransition() Fragment 1->Fragment 2 飞入动画;
setSharedElementReturnTransition() Fragment 2->Fragment 1 飞回动画;

Note that you need to call these methods on the second Fragment. If you set these on the originating Fragment, nothing will happen.

注意:以上2个方法在Fragment 2调用,如在Fragment 1调用则无响应。

You can animate the transition for all non-shared Views as well. For these Views, use setEnterTransition()setExitTransition()setReturnTransition(), andsetReenterTransition() on the appropriate Fragment.


Each of these methods takes in a single parameter, which is the Transitionanimation to use for the transition.


We are going to keep our animations fairly simple. We will use a custom transition for the movement of the image (more on that in a second), and aFade exit transition.


Fragment 1移动到Fragment 2,然后退出的时候消失。

Transition animation classes

Android provides some pre-made transition animations that are suitable for many use cases. Fade will perform a simple fade. Slide will slide views in from the sides of the screen. Explode can be fun- views will all move away from a particular focal point. Finally, AutoTransition will fade, move, and resize. These are just a few examples- explore the transition package for yourself to find more!

I mentioned that we need a custom transition to move our image. Here it is:

This transition is just a set of three transitions that will play together:

If you are curious about how these three interact together, try out the sample app and try removing one at a time to see how the animation breaks.

You can also define more complex transitions like this using XML. If you prefer XML, check out the Transition documentation.

Putting it all together

Our final code for performing this transition is fairly simple:

We are using our custom DetailsTransition for our shared element enter and return animation. All the other views in our first screen will exit with a Fadetransition, and the non-shared views in the second fragment will enter with aFade as well.

There you have it! An easy to implement transition between two Fragments!