AndroidSchedulers
class, which provides ready-made schedulers for Android-specific threads. Need to run code on a UI thread? No problem - use AndroidSchedulers.mainThread()
: retrofitService.getImage(url) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(bitmap -> myImageView.setImageBitmap(bitmap));
Handler
, you can create a scheduler associated with it with HandlerThreadScheduler
1 .AndroidObservable
, providing opportunities for working with the life cycle of some classes from the Android SDK. It has the bindActivity()()
and bindFragment()
operators that not only automatically use AndroidSchedulers.mainThread()
for monitoring, but also stop generating data when your Activity
or Fragment
starts to complete its work (so you won’t get into a mess trying to change their state when it cannot be done). AndroidObservable.bindActivity(this, retrofitService.getImage(url)) .subscribeOn(Schedulers.io()) .subscribe(bitmap -> myImageView.setImageBitmap(bitmap));
AndroidObservable.fromBroadcast()
, which allows you to create an Observable
that works as a BroadcastReceiver
. So, for example, you can receive a notification when the network status changes: IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); AndroidObservable.fromBroadcast(context, filter) .subscribe(intent -> handleConnectivityChange(intent));
ViewObservable
that adds bindings to the View
. It, among other things, contains the ViewObservable.clicks()
operators if you want to receive a notification whenever a click on the View
occurs, and ViewObservable.text()
, which is triggered whenever a TextView
changes its content. ViewObservable.clicks(mCardNameEditText, false) .subscribe(view -> handleClick(view));
Callback
: @GET("/user/{id}/photo") void getUserPhoto(@Path("id") int id, Callback<Photo> cb);
Observable
instead: @GET("/user/{id}/photo") Observable<Photo> getUserPhoto(@Path("id") int id);
Observable
as soon as you wish, it will be possible not only to obtain data from it, but also to transform it on the fly!Observable
support included in Retrofit also makes it easy to combine several REST requests together. For example, we have two api methods, the first one returns a photo, and the second one - its metadata. We can put the results of these queries together: Observable.zip( service.getUserPhoto(id), service.getPhotoMetadata(id), (photo, metadata) -> createPhotoWithData(photo, metadata)) .subscribe(photoWithData -> showPhoto(photoWithData));
flatMap()
). Now I wanted to show how easy it is to collect several REST requests into one using a bunch of RxJava + Retrofit.Observables
is great, but what if you have another library that you have never heard of? Or you have some old code that you would like to change without much effort so that he could work with Observable
. Simply put, how do you connect the old code with the new one without rewriting everything?Observable.just()
and Observable.from()
: private Object oldMethod() { ... } public Observable<Object> newMethod() { return Observable.just(oldMethod()); }
oldMethod()
executes quickly, but what if it is not? You will block the entire stream, because oldMethod()
will be called oldMethod()
, and then its result will be passed to Observable.just()
.Observable.defer()
: private Object slowBlockingMethod() { ... } public Observable<Object> newMethod() { return Observable.defer(() -> Observable.just(slowBlockingMethod())); }
Observable
you receive will not call slowBlockingMethod()
until you subscribe to it.Activity
when working with RxJava? There are a couple of problems that make themselves known again and again:ListView
. What if during the execution of the request, the user turns the phone? It would be necessary to resume the execution of the request, but how?Observables
that hold a reference to Context
.Context
(which is not so difficult if you work with Views
!) If the Observable
does not complete its work on time, at some point you will find that you are not can free up a large amount of memory.Observable
, without repeating its work. In particular, cache()
(or replay()
) will continue the previously executed query, even if you have already unsubscribed. This means that you can continue working after the re-creation of the Activity
: Observable<Photo> request = service.getUserPhoto(id).cache(); Subscription sub = request.subscribe(photo -> handleUserPhoto(photo)); // ... Activity ... sub.unsubscribe(); // ... Activity ... request.subscribe(photo -> handleUserPhoto(photo));
request
in both cases; thus, the query it performs will be executed only once. Where you save your request
is up to you, but, as is the case with all life-cycle decisions, this should be a place that is going through the changes generated by the life cycle (retained fragment, singleton, etc.)CompositeSubscription
to store all your subscriptions, and unsubscribe all from them in onDestroy()
or onDestroyView()
: private CompositeSubscription mCompositeSubscription = new CompositeSubscription(); private void doSomething() { mCompositeSubscription.add( AndroidObservable.bindActivity(this, Observable.just("Hello, World!")) .subscribe(s -> System.out.println(s))); } @Override protected void onDestroy() { super.onDestroy(); mCompositeSubscription.unsubscribe(); }
Activity
/ Fragment
containing a CompositeSubscription
, through which you will later save all your subscriptions, and which will automatically be cleared.CompositeSubscription.unsubscribe()
, this instance of CompositeSubscription
will no longer be available for use (that is, you can, of course, add subscriptions to it, but it will immediately unsubscribe()
) on them! If you want to continue to use the CompositeSubscription
in the future, you will have to create a new instance.AndroidSchedulers.mainThread()
uses within itself HandlerThreadScheduler
.Source: https://habr.com/ru/post/265997/
All Articles