Rx is the meaning of responsive programming, essentially the observer pattern, which is an asynchronous response based on the Observer (Observer) and the Subscriber (Subscriber). Background threads are often used in Android programming and can be used this way. The current asynchronous programming approach can cause some problems, such as
(1) Asynctasks can easily lead toMemory leaks. (2) cursorloaders with aContentProviderrequire aLarge amount ofConfiguration andBoilerplate code toSetup. (3) Services is intended forLonger running background tasks and notFast-finishing operations, such asMakingaNetwork callorLoading content from aDatabase.
Rxandroid from Rxjava, on the basis of Rxjava expansion of some Android features, has released 1.0 version, let's see how to use it.
1. Preparation
Create a new HelloWorld program. Configuration build.gradle
, add rxandroid Library and Lamada expression support, and butterknife.
plugins { "me.tatarka.retrolambda""3.2.2"}...android { ... compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }}dependencies { ... ‘com.jakewharton:butterknife:7.0.1‘ ‘io.reactivex:rxandroid:1.0.1‘}
Lambda expression support is not required and can make your code more concise and reduce the appearance of anonymous classes.
2. Page
The page is very simple, set three buttons, trigger time-consuming threading operations, respectively, using the main thread, Asynctasks
Rx mode call, observe the state of Processbar.
<?xml version= "1.0" encoding= "Utf-8"?><Relativelayout xmlns:android="Http://schemas.android.com/apk/res/android" Xmlns:app="Http://schemas.android.com/apk/res-auto" Xmlns:tools="Http://schemas.android.com/tools" Android:layout_width="Match_parent" Android:layout_height="Match_parent" Android:paddingbottom="@dimen/activity_vertical_margin" Android:paddingleft="@dimen/activity_horizontal_margin" Android:paddingright="@dimen/activity_horizontal_margin" Android:paddingtop="@dimen/activity_vertical_margin" App:layout_behavior="@string/appbar_scrolling_view_behavior" Tools:context=". Mainactivity " Tools:showin="@layout/activity_main"> <button android:id = "@+id/main_thread" android:layout_width
= "wrap_content" android:layout_height = "wrap_content" android:layout_centerhorizontal = "true" Span class= "Hljs-attribute" >android:text = "main thread" /> <button android:id = "@+id/main_async" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_below = "@id/main_thread" android:layout_centerhorizontal = android:text =" asynctasks "/> <button android:id = "@+id/main_rx" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_below =" @id/main_async " android:layout_centerhorizontal = "true" android:text = "Rx" /> <ProgressBarandroid:layout_width="Wrap_content"android:layout_height ="Wrap_content"android:indeterminate="true"android:layout_centervertical ="true"android:layout_centerhorizontal="true"/> </relativelayout>
3. Logic
Add a blocking task that performs 5 seconds of successful feedback.
// 长时间运行的任务 privatelongRunningOperation() { try { Thread.sleep(5000); catch (Exception e) { Log.e("DEBUG", e.toString()); } return"Complete!"; }
When the main thread executes, it causes the UI to get stuck
// 线程运行 mThreadButton.setOnClickListener(v -> { mThreadButton.setEnabled(false); longRunningOperation(); Snackbar.make(mRootView, longRunningOperation(), Snackbar.LENGTH_LONG).show(); mThreadButton.setEnabled(true); });
Asynchronous Thread execution
//async thread private Span class= "Hljs-class" >class myasynctasks Span class= "Hljs-keyword" >extends asynctask < Void , void , string > { @Override protected void OnPostExecute (String s) { Snackbar.make (Mrootview, S, Snackbar.length_long). Show (); masyncbutton.setenabled (true ); } @Override protected String Doinback Ground (Void ... params) {return longrunningoperation (); } }
// 异步运行 mAsyncButton.-> { mAsyncButton.setEnabled(false); new MyAsyncTasks().execute(); });
In a responsive manner, the thread that uses IO threading, the main thread response, or other threads can be processed, such as Schedulers.io()
threads that process IO, Schedulers.computation()
compute threads, Schedulers.newThread()
newly created threads.
//With IO threading, main thread responseobservable<string> Observable = Observable.create (NewObservable.onsubscribe<string> () {@Override Public void Pager(SUBSCRIBER<?Superstring> subscriber) {Subscriber.onnext (longrunningoperation ()); Subscriber.oncompleted (); }}). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ());//Responsive OperationMrxbutton.setonclicklistener (V, {mrxbutton.setenabled (false); Observable.subscribe (NewSubscriber<string> () {@Override Public void oncompleted() {mrxbutton.setenabled (true); }@Override Public void OnError(Throwable e) { }@Override Public void OnNext(String s) {Snackbar.make (Mrootview, S, Snackbar.length_long). Show (); } }); });
With responsive programming you can better handle memory leaks, the code is more elegant and readable, and it's easier to choose between thread and listener threads. When destroy, you can close an asynchronous task that is executing. There are some other advantages, just refer to the website.
Github
OK, use the responsive, asynchronous way of programming.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Rxandroid Brief Introduction