【问题标题】:Using Observable.from and flatMap to perform operation on each item in an Array, onComplete is not being called使用 Observable.from 和 flatMap 对 Array 中的每个项目执行操作,不会调用 onComplete
【发布时间】:2014-05-19 11:34:12
【问题描述】:

我正在使用 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();
        }
});

【问题讨论】:

    标签: android reactive-programming rx-java


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      相关资源
      最近更新 更多