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

io.rtr.alchemy.caching.CacheStrategyIterable Maven / Gradle / Ivy

There is a newer version: 2.2.16
Show newest version
package io.rtr.alchemy.caching;

import io.rtr.alchemy.models.Experiment;

import java.util.Iterator;

/**
 * Implements a wrapper around iterable of Experiment in order to trigger the cache strategy as
 * results are retrieved
 */
public class CacheStrategyIterable implements Iterable {
    private final Iterable iterable;
    private final CachingContext context;
    private final CacheStrategy strategy;

    public CacheStrategyIterable(
            Iterable iterable, CachingContext context, CacheStrategy strategy) {
        this.iterable = iterable;
        this.context = context;
        this.strategy = strategy;
    }

    @Override
    public Iterator iterator() {
        return new CacheStrategyIterator(iterable.iterator());
    }

    private class CacheStrategyIterator implements Iterator {
        private final Iterator iterator;
        private Experiment current;

        private CacheStrategyIterator(Iterator iterator) {
            this.iterator = iterator;
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Override
        public Experiment next() {
            final Experiment next = iterator.next();
            strategy.onLoad(next, context);
            current = next;
            return next;
        }

        @Override
        public void remove() {
            iterator.remove();
            strategy.onDelete(current.getName(), context);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy