RxJava from entry to never leave (7) - groupBy

Posted by raker7 on Tue, 17 Dec 2019 19:00:50 +0100

In RxJava, groupBy divides an Observable into several Observable sets. Each of them transmits a subsequence of the original Observable. Which data item is transmitted by which Observable is determined by a function. This function specifies a Key for each item, and the data with the same Key will be transmitted by the same Observable.

Let's look at an example to see:

        ArrayList<Object> list = new ArrayList<Object>();
        list.add(new Person());
        list.add(new Person());
        list.add(new Student());
        list.add(new Student());
        list.add(new Person());
        list.add(new Student());
        list.add(new Student());
        Observable.from(list)
                .groupBy(new Func1<Object, Integer>() {
                    @Override
                    public Integer call(Object o) {
                        if (o.getClass().getName().equals(Person.class.getName())) {
                            return 1;
                        } else {
                            return 2;
                        }
                    }
                })
                .subscribe(integerObjectGroupedObservable -> {
                    int key = integerObjectGroupedObservable.getKey();

                    switch (key) {
                        case 1:

                            integerObjectGroupedObservable.subscribe(new Action1<Object>() {
                                @Override
                                public void call(Object o) {
                                    Log.e("groupBy", "call: Receive Person object");
                                }
                            });


                            break;
                        case 2:

                            integerObjectGroupedObservable.subscribe(new Action1<Object>() {
                                @Override
                                public void call(Object o) {
                                    Log.e("groupBy", "call: Receive Student object");
                                }
                            });

                            break;
                    }
                });

Result:

call: receive Person object
 call: receive Person object
 call: receive Student object
 call: receive Student object
 call: receive Person object
 call: receive Student object
 call: receive Student object

In the Func1() function of GroupBy, group by your logic and return the key flag of the group corresponding to each information. For example, each flag of my group is of Integer type. GroupBy will return a special subclass of Observable, GroupedObservable, which has an extra method getKey(), which can be used to obtain the current information group.

More interesting content. Welcome to my WeChat public address, Android motor vehicle.

Topics: Android