Rxjava tolist() not completing

2019-07-19 08:33发布

问题:

I have a problem with my RxJava callchain. The toList is not working properly. I would guess that it is that the toList() needs something to complete. That is why it is stuck. But i do not know how to solve this issue

The code

        mModel.getLocations()
            .flatMapIterable(new Function<List<Location>, List<Location>>(){
                @Override
                public List<Location> apply(final List<Location> locations) throws Exception {
                    return locations;
                }
            })
            .filter(new Predicate<Location>() {
                @Override
                public boolean test(final Location location) throws Exception {
                    return location.searchExistInNameOrKeyWord(input);
                }
            })
            .toList()
            .map(new Function<List<Location>, List<Location>>() {
                @Override
                public List<Location> apply(List<Location> locations) throws Exception {                     
                    /** Doing some random work with the list and then returning */
                }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<List<Location>>() {
                @Override
                public void accept(final List<Location> locations) throws Exception {
                    mView.setAdapterItems(locations);
                }
            });

Maybe someone that is a lot better than me at RxJava could pinpoint what i am doing wrong.

Update

@Query("SELECT * from location")
Flowable<List<Location>> loadAllLocations();

The mModel.getLocations() just calls the loadAllLocations like above from the Room percistance storage

回答1:

I've never used Room before but according to this article: https://medium.com/google-developers/room-rxjava-acb0cd4f3757

Now, every time the user data is updated, our Flowable object will emit automatically, allowing you to update the UI based on the latest data. The Flowable will emit only when the query result contains at least a row. When there is no data to match the query, the Flowable will not emit, neither onNext nor onError.

So, Flowable reacts on every data change and that means onComplete would never be called. In that case you cannot use toList() operator because this stream will never complete.



回答2:

The Key Point for toList() operator is that It will wait for all the items to be emitted. Once its done mean onComplete() method must get called and there we will get our desirable result. If we are not using onComplete() or because of some reason onComplete() is not getting called then nothing will print.