Search code examples
rx-java2rx-android

How to use doOnNext, doOnSubscribe and doOnComplete?


New to RxJava2/RxAndroid and Android development, but am pretty familiar with Java. However, I've ran into quite a roadblock when trying to "optimize" and be able to update the UI between a bunch of calls to the same resource.

My code is as follows:

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();
    });
}

If I remove the doOnSubscribe, doOnNext and doOnComplete I get no errors in Android Studio, but if I use any of them I get Incompatible types. Required: Observable<[...].ItemInfo[]>. Found: Observable<java.lang.Object>

I'm using RxAndroid 2.1.1 and RxJava 2.2.16.

Any ideas?


Solution

  • Since you are adding a chain of method calls, the compiler is just unable to correctly guess the type for the generic parameter in Observable.create. You can set it explicitly using Observable.<ItemInfo[]>create(...).