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
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
34
35 for (int i = 0; i < parts.length - 1; i++) {
36 if (observer.isUnsubscribed()) {
37
38 return null;
39 }
40 observer.onNext(parts[i]);
41 }
42
43
44
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
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 }