ashughes
ashughes

Reputation: 7233

How to check subscription status when not using Observable.create()?

Say you have some long running task wrapped by an observable:

Observable.fromCallable(new Callable<String>() {
    @Override
    public String call() throws Exception {
        return longRunningTask();
    }
}

Is there any way to check whether the observable has been unsubscribed to determine if we should cancel the work and bail out?

More specifically, is it possible to check the status of a subscription (e.g. isUnsubscribed()) when using Observable.defer() or Observable.fromCallable()?

I'm aware that you can check subscriber.isUnsubscribed() when using Observable.create(), however, since it's ill-advised to use Observable.create(), how can this be done with other operators?

Upvotes: 2

Views: 1195

Answers (2)

akarnokd
akarnokd

Reputation: 69997

The fromCallable doesn't expose the consumer. For this, you need create with a body such as the following:

final SingleDelayedProducer<T> singleDelayedProducer = 
    new  SingleDelayedProducer<T>(subscriber);

subscriber.setProducer(singleDelayedProducer);

try {
    T result;

    // computation

    if (subscriber.isUnsubscribed()) {
        return;
    }

    // more computation

    result = ...

    singleDelayedProducer.setValue(result);
} catch (Throwable t) {
    Exceptions.throwOrReport(t, subscriber);
}

Upvotes: 0

Martin
Martin

Reputation: 522

What about using Observable.doOnSubscribe(Action0) and Observable.doOnUnsubscribe(Action0). You can count the subscriptions and when there are none you can stop the job.

Greetings, Martin

Upvotes: 1

Related Questions