使用Observable.from和flatMap对Array中的每个项执行操作时,不会调用onComplete

时间:2014-05-18 15:08:43

标签: android reactive-programming rx-java

我使用Rx-Java为数组中的每个项目执行api调用。我希望一旦所有操作完成但是没有被调用,就会调用OnComplete操作。对数组项的操作确实成功完成。

public Observable<User> report(Long[] userIds) {
    return Observable.from(userIds).flatMap(new Func1<Long, Observable<User>>() {
        @Override
        public Observable<User> call(Long id) {
            return reportSpam(id);
        }
    });
}

public Observable<User> report(final Long id) {
    return Observable.create(new Observable.OnSubscribe<User>() {
        @Override
        public void call(Subscriber<? super User> subscriber) {
            try {
                twitter.report(id);
            } catch (TwitterException e) {
                subscriber.onError(e);
            }
        }
    });
}

final Long[] usersIds = selectedToUsersIds();

report(usersIds).subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<User>() {
        @Override
        public void call(User user) {
            //nothing to do here, don't even need the User
        }
    }, new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
        //handle this
        }
    }, new Action0() {
        @Override
        public void call() {
            Toast.makeText(getActivity(), getString(R.string.reported_for_spam, usersIds.length), Toast.LENGTH_SHORT).show();
        }
});

1 个答案:

答案 0 :(得分:1)

您需要在subscriber.onCompleted()中致电Observable<User> report(final Long id)Observable应始终在流的末尾调用onCompletedonError