All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.davidmoten.rx.UnsubscribeDetector Maven / Gradle / Ivy

There is a newer version: 0.7.19
Show newest version
package com.github.davidmoten.rx;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import rx.Observable.Operator;
import rx.Subscriber;
import rx.Subscription;

/**
 * Provides a {@link CountDownLatch} to assist with detecting unsubscribe calls.
 * 
 * @param 
 */
public class UnsubscribeDetector implements Operator {

    private static final Logger log = LoggerFactory.getLogger(UnsubscribeDetector.class);

    private final CountDownLatch latch;

    /**
     * Constructor.
     */
    public UnsubscribeDetector() {
        latch = new CountDownLatch(1);
    }

    @Override
    public Subscriber call(Subscriber subscriber) {
        subscriber.add(new Subscription() {

            private final AtomicBoolean subscribed = new AtomicBoolean(true);

            @Override
            public void unsubscribe() {
                latch.countDown();
                subscribed.set(false);
                log.info("unsubscribed");
            }

            @Override
            public boolean isUnsubscribed() {
                return subscribed.get();
            }
        });
        return subscriber;
    }

    /**
     * Returns a latch that will be at zero if one unsubscribe has occurred.
     * 
     * @return
     */
    public CountDownLatch latch() {
        return latch;
    }

    /**
     * Factory method.
     * 
     * @return
     */
    public static  UnsubscribeDetector detect() {
        return new UnsubscribeDetector();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy