Skip to content

Commit 3429d45

Browse files
committed
Make byLine handle carriage return, carriage return newline, and newline equally.
1 parent d8306c3 commit 3429d45

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/main/java/rx/observables/StringObservable.java

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -551,15 +551,23 @@ public void onNext(String t) {
551551
}
552552

553553
/**
554-
* Splits the {@link Observable} of Strings by lines and numbers them (zero based index)
554+
* Splits the {@link Observable} of Strings by line ending characters in a platform independent way. It is equivalent to
555+
* <pre>split(src, "(\r\n)|(\n)|(\r)")</pre>
555556
* <p>
556557
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/St.byLine.png" alt="">
557558
*
558559
* @param source
559560
* @return the Observable conaining the split lines of the source
561+
* @see StringObservable#split(Observable, Pattern)
560562
*/
561563
public static Observable<String> byLine(Observable<String> source) {
562-
return split(source, System.getProperty("line.separator"));
564+
return split(source, ByLinePatternHolder.BY_LINE);
565+
}
566+
/**
567+
* Lazy initialization of the pattern.
568+
*/
569+
private static final class ByLinePatternHolder {
570+
private static final Pattern BY_LINE = Pattern.compile("(\r\n)|(\n)|(\r)");
563571
}
564572

565573
/**

src/test/java/rx/observables/StringObservableTest.java

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -356,8 +356,30 @@ public synchronized int read(byte[] b, int off, int len) {
356356
}
357357

358358
@Test
359-
public void testByLine() {
360-
String newLine = System.getProperty("line.separator");
359+
public void testByLine_Newline() {
360+
String newLine = String.valueOf(new char[] { 10 });
361+
362+
List<String> lines = byLine(
363+
Observable.from(Arrays.asList("qwer", newLine + "asdf" + newLine, "zx", "cv")))
364+
.toList().toBlocking().single();
365+
366+
assertEquals(Arrays.asList("qwer", "asdf", "zxcv"), lines);
367+
}
368+
369+
@Test
370+
public void testByLine_CarriageNewline() {
371+
String newLine = String.valueOf(new char[] { 13, 10 });
372+
373+
List<String> lines = byLine(
374+
Observable.from(Arrays.asList("qwer", newLine + "asdf" + newLine, "zx", "cv")))
375+
.toList().toBlocking().single();
376+
377+
assertEquals(Arrays.asList("qwer", "asdf", "zxcv"), lines);
378+
}
379+
380+
@Test
381+
public void testByLine_Carriage() {
382+
String newLine = String.valueOf(new char[] { 13 });
361383

362384
List<String> lines = byLine(
363385
Observable.from(Arrays.asList("qwer", newLine + "asdf" + newLine, "zx", "cv")))

0 commit comments

Comments
 (0)