3

I have the following code. It's basically an attempt to send all data from a specific SQLite table to DynamoDB:

Observable.create(new Observable.OnSubscribe<Area>() {
    @Override
    public void call(Subscriber<? super Area> subscriber) {
        try {
            for (Area item : areaDao.listAll()) {
                subscriber.onNext(item);
            }
            subscriber.onCompleted();
        } catch (Exception e) {
            subscriber.onError(e);
        }
    }
}).flatMap(new Func1<Area, Observable<Area>>() {
    @Override
    public Observable<Area> call(Area area) {
        dynamoDBMapper.save(area);
        return Observable.just(area);
    }
}).observeOn(
        AndroidSchedulers.mainThread()
).doOnError(new Action1<Throwable>() {
    @Override
    public void call(Throwable throwable) {
        Log.w("AreaHandler", "Could not upload area", throwable);
    }
}).doOnCompleted(new Action0() {
    @Override
    public void call() {
        Toast.makeText(ctx, R.string.toast_upload_successful, Toast.LENGTH_SHORT).show();
    }
}).subscribeOn(
        Schedulers.io()
).subscribe(new Action1<Area>() {
    @Override
    public void call(Area area) {
        areaDao.delete(area.getId());
    }
});

I'm trying to run it on an emulator with disabled Internet connectivity, and what happens is that the Dynamo client does a couple of (failed) retries, then an exception is thrown and it crashes the app. From what I read in the docs, the exception should be swallowed by doOnError instead of being let out to the wild and killing the process.

What am I missing?

pstobiecki
  • 1,804
  • 1
  • 17
  • 30

1 Answers1

4

You are grabbing the error in the wrong place. doOnError is for side effects. It does not handle the error.

Option 1. Pass in two Action1

Observable.just(1, 2, 3)
            .subscribe(
                    new Action1<Integer>() {
                        @Override
                        public void call(Integer integer) {
                            System.out.println(integer);
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            System.err.print(throwable);
                        }
                    });

Option 2: Pass in an Observer

    Observable.just(1, 2, 3)
            .subscribe(new Observer<Integer>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable throwable) {
                    System.err.print(throwable);
                }

                @Override
                public void onNext(Integer integer) {
                    System.out.println(integer);
                }
            });
cyroxis
  • 3,661
  • 22
  • 37