Skip to content

SideEffect Pipes

drachimera edited this page Jul 15, 2012 · 4 revisions

A side-effect based pipe will emit the incoming object unaltered. However, during that process, a computation is effected. This computation can be used to yield a computational side-effect.

Generic SideEffect Pipe

The generic side-effect pipe is SideEffectFunctionPipe. A SideEffectFunctionPipe takes a PipeFunction (see Pipe Types) that computes on S and emits S. However, the provided PipeFunction provides a side-effect computation. An example PipeFunction is provided below:

public class CharTotalPipeFunction implements PipeFunction<String, Integer> {
  
  private final Integer count;
  
  public CharCountPipeFunction(Integer count) {
    this.count = count;
  }

  public Object compute(String argument) {
     this.count.getAndAdd(argument.length())
     return null;
  }
}

When put in the context of a SideEffectClosurePipe, the code looks as follows:

int count = 0;
Pipe<String, String> pipe = new SideEffectFunctionPipe<String>(new CharTotalPipeFunction(count));
pipe.setStarts(Arrays.asList("tell", "me", "your", "name"));
// the results of the iteration are: "tell", "me", "your", "name"
assert count.get() == 14;
Clone this wiki locally