The previous chapter was the last chapter about RxJava's Observable creation and manipulation. We learned how to combine two or more Observables, to join them, zip them, merge them, and how to create a new Observable to fit our particular needs.
In this chapter, we will raise the bar and see how to easily deal with multithreading and concurrent programming using RxJava's Schedulers. We will learn how to create network operations, memory accesses, and time-consuming tasks in a reactive way.
To gain information about common issues that could be present in our code base, we are going to enable StrictMode
in our app.
StrictMode
helps us detect sensitive activities, such as disk accesses or network calls that we are accidentally performing on the main thread. As you know, performing heavy or long tasks on the main thread is a no-go, because the main thread for Android apps is the UI thread and it should be used only for UI related operations: it's the only way to get smooth animations and a responsive app.
To enable StrictMode
in our app, we just need to add a few lines to MainActivity
, and the onCreate()
methods will look like this:
@Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog() .build()); } }
We don't want it enabled all the time, so we limit it only to debug builds. This configuration will report every violation about the main thread usage and every violation concerning possible memory leaks: Activities
, BroadcastReceivers
, Sqlite
objects, and more.
Choosing penaltyLog()
, StrictMode
will print a message on logcat when a violation occurs.
52.15.129.253