View Javadoc
1   package com.github.davidmoten.rx.internal.operators;
2   
3   import java.util.regex.Pattern;
4   
5   import com.github.davidmoten.rx.Functions;
6   
7   import rx.Observable.Transformer;
8   import rx.Subscriber;
9   import rx.functions.Func0;
10  import rx.functions.Func2;
11  import rx.functions.Func3;
12  
13  public final class TransformerStringSplit {
14  
15  	public static <T> Transformer<String, String> split(final String pattern, final Pattern compiledPattern) {
16  		Func0<String> initialState = Functions.constant0(null);
17  		Func3<String, String, Subscriber<String>, String> transition = new Func3<String, String, Subscriber<String>, String>() {
18  
19  			@Override
20  			public String call(String leftOver, String s, Subscriber<String> observer) {
21                  // prepend leftover to the string before splitting
22  			    if (leftOver != null) {
23  			        s = leftOver + s;
24  			    }
25  			    
26  				String[] parts;
27  				if (compiledPattern != null) {
28  					parts = compiledPattern.split(s, -1);
29  				} else {
30  					parts = s.split(pattern, -1);
31  				}
32  
33  				// can emit all parts except the last part because it hasn't
34  				// been terminated by the pattern/end-of-stream yet
35  				for (int i = 0; i < parts.length - 1; i++) {
36  					if (observer.isUnsubscribed()) {
37  						// won't be used so can return null
38  						return null;
39  					}
40  					observer.onNext(parts[i]);
41  				}
42  
43  				// we have to assign the last part as leftOver because we
44  				// don't know if it has been terminated yet
45  				return parts[parts.length - 1];
46  			}
47  		};
48  
49  		Func2<String, Subscriber<String>, Boolean> completion = new Func2<String, Subscriber<String>, Boolean>() {
50  
51  			@Override
52  			public Boolean call(String leftOver, Subscriber<String> observer) {
53  				if (leftOver != null && !observer.isUnsubscribed())
54  					observer.onNext(leftOver);
55  				// TODO is this check needed?
56  				if (!observer.isUnsubscribed())
57  					observer.onCompleted();
58  				return true;
59  			}
60  		};
61  		return com.github.davidmoten.rx.Transformers.stateMachine(initialState, transition, completion);
62  	}
63  
64  }