RXAndroid Part 3 PublishSubject

In the previous series of tutorial on RxAndroid part 1 and 2 we have seen about basics of RxAndroid like creating observable , observer and subscription and how to apply operators to observable for manipulating data emitted by observable . In this tutorial we will see one of the interesting concept of Rxjava called Subject.

Subjects are special objects that are both an Observable and an Observer. you can think of it like a pipe You can put things into one end of the Subject and it will come out the other.

There are several types of Subjects in this tutorial we will see one of the simplest subject : a PublishSubject. With a PublishSubject, as soon as you put something in one end of the pipe it immediately comes out the other.




Lets understand the concept by a sample example increment counter on button click .

1.  Create and Subscribe 


Inside the onResume Create and Subscribe for publishSubject .
This is like subscribing to one end of the pipe to listen when there is data emission on another end .

private PublishSubject<Integer> mCounterEmitter;
private Subscription mSubscription;
private int mCounter = 0;

mCounterEmitter = PublishSubject.create();

mSubscription = mCounterEmitter.subscribe(
        new Observer<Integer>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(Integer integer) {
                textView.setText(String.valueOf(integer));
            }
        });

2. Publish (onNext)


Set the onClickListener for button view , inside the onClick method increment the mCounter variable and call onNext method by passing mCounter variable as a paramter to it .
This is like emitting data from one of end of the pipe .

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mCounter++;
        mCounterEmitter.onNext(mCounter);
    }
});

3. UnSubscribe


if (mSubscription != null && !mSubscription.isUnsubscribed()) {
    mSubscription.unsubscribe();
}

Code:https://github.com/hdpavan/RxAndroidSample/blob/master/app/src/main/java/com/tutorialsbuzz/rxandroidsample/Examples/FragmentExample12.java

Debounce

Now lets make an sample example where user search for countries by name using pubjectSubject .

The following example is similar to Filtering RecyclerView Using SearchView but the different is there we are searching for data which is stored  in local variable and here in this example we make network request for user search query and show the result  .

1. Create and Subscribe


Inside the onResume create and subscribe for publishSubject. as you can notice we are calling debounce() on publishsubject object . So what is debounce ? Every Single time the user adds or remove character in SearchView . It is not good to send out a request to the server on every single keystroke .
What is Debounce ?

The debounce operator emits only those items from the source Observable that are not followed by another item within a specified duration.


private PublishSubject<String> mSearchResultsSubject;
private Subscription mSearchSubscription;

mSearchResultsSubject = PublishSubject.create();
mSearchSubscription = mSearchResultsSubject
        .debounce(400, TimeUnit.MILLISECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .map(new Func1<String, List<String>>() {
            @Override
            public List<String> call(String data) {
                return mRestClient.searchForCity(data);
            }
        })

        .subscribe(new Observer<List<String>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(List<String> cities) {
                handleSearchResults(cities);
            }
        });

This is what debounce() allows us to do. It tells mSearchResultsSubject to only emit the last value that came into it after nothing new has come into the mSearchResultsSubject for 400 milliseconds .

2. Publish Text Change Listener


Adding TextChangeL Listener to SearchView , Inside the onQueryTextChange call the onNext method using publishSubject object by passing string (new text) .
@Override
public boolean onQueryTextChange(String newText) {
    mSearchResultsSubject.onNext(newText);
    return true;
}

3. Handle Search Result


This method is used called inside the onNext method for updating UI (recylcerView with filter list).
private void handleSearchResults(List<String> cities) {
    if (cities.isEmpty()) {
        showNoSearchResults();
    } else {
        showSearchResults(cities);
    }
}

4. UnSubscribe


Finally inside the onDestroy method call UnSubscribe on subscription object.
if (mSearchSubscription != null && !mSearchSubscription.isUnsubscribed()) {
    mSearchSubscription.unsubscribe();
}



Code:https://github.com/hdpavan/RxAndroidSample/blob/master/app/src/main/java/com/tutorialsbuzz/rxandroidsample/Examples/FragmentExample13.java

20 comments:

Melanie Glastrong said...

Such a nice blog.

I have read an amazing article here.

三五创业网 said...

找了好久才找到这里,来了就不想走!

补肾壮阳 said...

大气博客,让人留恋不舍!

jie.la said...

good a blog!

极品单拼域名 said...

两个极品单拼域名出售:
-------------------------
jie.la:
借贷放款行业极品单拼大米。

一口价购买地址:
https://auctions.godaddy.com/trpItemListing.aspx?&miid=251070637
-------------------------
rong.la:
金融、融资行业极品单拼大米。

一口价购买地址:
https://auctions.godaddy.com/trpItemListing.aspx?miid=251071138
-------------------------
群发,打扰了!如有意联系邮箱:feibaohu@qq.com

无意者勿联系,不回!
-------------------------

增大 said...

受益匪浅,感触良多!

增大网 said...

我踩故我在,下次还会来!

百约不得姐 said...

为啥我又来,因为这里百看不厌!

增大网 said...

日看博客两三篇,每天生活乐无边!

吊炸天 said...

大神!受我一拜!

jinbo said...

一个博客能让人流连忘返,讲真,靠的是实力!

增大网 said...

增大壮阳、丰乳缩阴、泡妞把妹,价值十万资料无限下。

逆向推荐,上线替下线赚钱,什么不用干,坐收二百万。

增大网:

111.zhuan.in

巨根增大网 said...

让人百看不厌的博客,真的不是很多!

藏金网 said...

这个博客就像一座宝藏,我是来掘金滴!

kitty23 said...

第一次看,感觉还挺新鲜!

948 said...

炎热夏天,闲来无事,拜读博客,消暑解闷!

藏金网 said...

生活不止眼前的苟且,还有博客和远方的田野!

爱就爱啦 said...

从百度点进来的,学习学习,呵呵!

闺房独自乐 said...

炎热的夏天,看到这样的博客瞬间清凉了许多!

罗拉套图网 said...

到你的博客走一趟,如同阳光洒在我脸上,心里暖洋洋!

Post a Comment