Skip to content

Commit

Permalink
fixed adding more filters to a subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
jorisguffens committed Dec 7, 2022
1 parent 63bf99f commit c0949ae
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 8 deletions.
11 changes: 11 additions & 0 deletions api/src/main/java/com/guflimc/brick/stats/api/event/Filter.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@

import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.List;

@FunctionalInterface
public interface Filter {
boolean test(@NotNull Event event);

static Filter allOf(Collection<Filter> filters) {
return event -> filters.stream().allMatch(f -> f.test(event));
}

static Filter allOf(Filter... filters) {
return allOf(List.of(filters));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,9 @@ public void unsubscribe() {
private class BrickSubscriptionBuilder extends AbstractSubscriptionBuilder {

private Subscription subscribe(@NotNull Filter extraFilter) {
Filter combined = event -> filter.test(event) && extraFilter.test(event);
return subscribe(new BrickSubscription(handler, combined));
List<Filter> filters = new ArrayList<>(this.filters);
filters.add(extraFilter);
return subscribe(new BrickSubscription(handler, Filter.allOf(filters)));
}

private Subscription subscribe(@NotNull BrickSubscription sub) {
Expand All @@ -222,10 +223,10 @@ public Subscription change() {

@Override
public Subscription interval(int interval) {
return subscribe(new BrickSubscription(handler, filter) {
return subscribe(new BrickSubscription(handler, Filter.allOf(filters)) {
@Override
public void execute(Event event) {
if (!filter.test(event)) {
if ( !filter.test(event) ) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@
import com.guflimc.brick.stats.api.event.SubscriptionBuilder;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractSubscriptionBuilder implements SubscriptionBuilder {

protected Filter filter = event -> true;
protected List<Filter> filters = new ArrayList<>();
protected EventHandler handler;

@Override
public SubscriptionBuilder filter(@NotNull Filter filter) {
this.filter = filter;
this.filters.add(filter);
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

public abstract class AbstractSubscription implements Subscription {

private final EventHandler handler;
private final Filter filter;
protected final EventHandler handler;
protected final Filter filter;

public AbstractSubscription(@NotNull EventHandler handler, @NotNull Filter filter) {
this.handler = handler;
Expand Down

0 comments on commit c0949ae

Please sign in to comment.