chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

How to use RxAndroid with kotlin

2017-10-29

This article is more for iOS developers who wants to put their hands on the Android Development, or for those who just want to enter the Android development world. There are no hard points in the article. In the tutorial, you are about to know:

  • Install how to install dependencies
  • Know how to use RXAndroid
  • Source code on github

Install the RxAndroid dependency

In Android, dependency is the similar concept of Cocoapod and Carthage in iOS, but with a more concise and eaiser way. WHY? As using 3rd party libraries in iOS may ask you to setup the lib path manually, sometimes if it is a swift lib, a bridge header must be created in order to compile.

Mordern Android dev is using gradle to manage all the necessary libs/modules/dependencies. In each of the Android project, you might find out more than one build.gradle file:

  • build.gradle in the root directory: specify overall project configuration
  • build.gradle in app directory: specify the configuration for current app

In the module build.gradle file add the following dependecies:

To use the same version of libs and modules through the whole project, assign the libs and module version number in the project build.gradle file:

Android Studio will ask for Sync now, do it and ide will install the related libs and modules.


RxAndroid

Like so many articles and tutorials taught you about Reactive programming. As an introduction tutorial, here we don't want to mention too much details on the principle behind. The idea is quite simple:

When there is any change on the component, some functions will be triggered.

We can use one simple example to get start. which has a textEdit on the screen, each time with user's input, the input text on the screen after 1 second.

Someone might say: I can use timer to do the sam thing. YES, surely you can. But what if you have more than 10 diff components. Creating a timer for each of them will take a while, plus they are hard to maintain. You probably can't remember the details after few months.

Step 1: Create an Observable

First make an Observable object

Step 2: Setup subscription to this Observable

THAT IS IT🚀🚀🚀🚀. Now you are able to see the text change. But wait, it crashed.

What is that??

Android does not allow to update UI from its main thread.

So in order to solve this, we'd better to put the code in a different thread:

Now when you rerun the program, you will find the crash is gone. The source code is at: https://github.com/arkilis/RxAndoridTextEdit


In Closing

In this turtorial, a few things have been covered:

  • Add dependecies to an Android project
  • Learn how to create one example with RxAndroid
  • Learn how to use Threading Model with RxAnroid

Reference

http://www.arkilis.me
https://github.com/ReactiveX/RxAndroid

arkilis

Comments: