Skip to content

Creating a Pipe

okram edited this page Jan 16, 2011 · 4 revisions

The pipes that come prepackaged with Pipes are not sufficient for every use case. In many situations, it will be necessary to create a pipe that will solve a particular mapping from an input to an output. Pipes make it easy to create new pipes with the AbstractPipe class. In AbstractPipe, there is a single method that needs to be implemented: AbstractPipe.processNextStart(). The example below demonstrates the internals of a simple pipe that maps a string to the number of characters contained in that string.

public class WordLengthPipe extends AbstractPipe<String, Integer> {
  public Integer processNextStart() {
    String start = this.starts.next();
    return start.length();
  }
}

The general pattern for filter-based pipes is explained with an example.

public class WordFilterPipe extends AbstractPipe<String,String> implements FilterPipe<S> {
  public String processNextStarts() {
    while(true) {
       String start = this.starts.next();
       if(start.length() > 4)
          return start;
    }
  }
}

A FilterPipe will usually make use of a while(true) loop that will continually pull in new objects. If the current object meets some criteria, it will be emitted, else, the while(true) will loop again and pull in a new object. There is no need to worry about handling NoSuchElementExceptions. If this.starts.next() throws a NoSuchElementException then this will be handled appropriately by AbstractPipe.

Clone this wiki locally