-->

Why is OnComplete not called in this code? (RxAndr

2019-07-25 17:43发布

问题:

I know OnComplete of a Observer is called when all the items are emitted. In the below code, I am putting data from a cursor to an ArrayList in a flatMap operator. My cursor has 100 entries ( c.getCount() gives 100 ) and the size of my list is 100. The onNext is called 100 times too. But the onComplete is not called. I am populating a listview in onComplete.

static int i = 0;
final List<String> ar = new ArrayList<>();
ListView lv = ...;
ArrayAdapter<String> adapter = ...;   
.
.
. 
q.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .flatMap(new Func1<SqlBrite.Query, Observable<String>>() {
                @Override
                public Observable<String> call(SqlBrite.Query query) {
                    Cursor c = query.run();
                    c.moveToFirst();
                    Log.d("testApp", String.valueOf(c.getCount())); // prints 100
                    do {
                        ar.add(c.getString(0));
                    } while (c.moveToNext());
                    Log.d("testApp", String.valueOf(ar.size())); // prints 100
                    return Observable.from(ar);
                }
            }).subscribe(new Observer<String>() {
                @Override
                public void onCompleted() {
                    Log.d("testApp", "onComplete called");
                    lv.setAdapter(adapter);
                }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(String s) {
                Log.d("testApp", "onNext called " + String .valueOf(++i) + " with " + s); // printed 100 times
                adapter.add(s);
            }
        });

The new stream of Observable is to complete after 100 but it does not.

Any help is appreciated, Thank You

回答1:

FlatMap operator merge your main stream with your flatMapped stream. Your observable will complete if q and your Observable from your array complete. So check why q doesn't no complete.