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

com.github.tix320.kiwi.api.reactive.publisher.CachedPublisher Maven / Gradle / Ivy

There is a newer version: 2.4.0
Show newest version
package com.github.tix320.kiwi.api.reactive.publisher;

import java.util.*;

import com.github.tix320.kiwi.internal.reactive.publisher.BasePublisher;

public final class CachedPublisher extends BasePublisher {

	private final List cache;

	public CachedPublisher() {
		this.cache = new LinkedList<>();
	}

	@Override
	protected boolean onSubscribe(InternalSubscription subscription) {
		publishFromCache(subscription);
		return true;
	}

	@Override
	public void publish(T object) {
		failIfCompleted();
		fillCache(object);
		Collection subscriptions = getSubscriptionsCopy();
		for (InternalSubscription subscription : subscriptions) {
			try {
				boolean needMore = subscription.onPublish(object);
				if (!needMore) {
					subscription.unsubscribe();
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void publish(T[] objects) {
		failIfCompleted();
		fillCache(objects);
		for (T object : objects) {
			publish(object);
		}
	}

	@Override
	public void publish(Iterable iterable) {
		failIfCompleted();
		for (T object : iterable) {
			fillCache(object);
			publish(object);
		}
	}

	public List getCache() {
		return Collections.unmodifiableList(cache);
	}

	private void fillCache(T object) {
		cache.add(object);
	}

	private void fillCache(T[] objects) {
		cache.addAll(Arrays.asList(objects));
	}

	private void publishFromCache(InternalSubscription subscription) {
		runAsync(() -> {
			for (T object : cache) {
				boolean needMore = subscription.onPublish(object);
				if (!needMore) {
					subscription.unsubscribe();
					break;
				}
			}
		});
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy