doOnNext、doOnSubscribe、doOnComplete如何使用?

How to use doOnNext, doOnSubscribe and doOnComplete?

RxJava2/RxAndroid 和 Android 开发的新手,但对 Java 非常熟悉。 但是,我 运行 在尝试 "optimize" 并且能够在对同一资源的一堆调用之间更新 UI 时遇到了很大的障碍。

我的代码如下:

private int batch = 0;
private int totalBatches = 0;
private List<ItemInfo> apiRetItems = new ArrayList<>();
private Observable<ItemInfo[]> apiGetItems(int[] ids) {
    int batchSize = 100;

    return Observable.create(emitter -> {
        int[] idpart = new int[0];

        for(int i = 0; i < ids.length; i += batchSize) {
            batch++;
            idpart = Arrays.copyOfRange(ids, i, Math.min(ids.length, i+batchSize));
            ItemInfo[] items = client.items().get(idpart);
            emitter.onNext(items);
        }
        emitter.onComplete();
    }).doOnSubscribe( __ -> {
        Log.d("GW2DB", "apiGetItems subscribed to with " + ids.length + " ids.");
        totalBatches = (int)Math.ceil(ids.length / batchSize);
        progressbarUpdate(0, totalBatches);
    }).doOnNext(items -> {
        Log.d("GW2DB", batch + " batches of " + totalBatches + " batches completed.");
        progressbarUpdate(batch, totalBatches);
    }).doOnComplete( () -> {
        Log.d("GW2DB", "Fetching items completed!");
        progressbarReset();
    });
}

如果我删除 doOnSubscribedoOnNextdoOnComplete,我在 Android Studio 中不会出现任何错误,但如果我使用它们中的任何一个,我会得到 Incompatible types. Required: Observable<[...].ItemInfo[]>. Found: Observable<java.lang.Object>

我正在使用 RxAndroid 2.1.1 和 RxJava 2.2.16。

有什么想法吗?

由于您添加了一系列方法调用,因此编译器无法正确猜测 Observable.create 中泛型参数的类型。您可以使用 Observable.<ItemInfo[]>create(...) 明确设置它。