Skip to content

Create an Observable that emits each char in the source String. #1888

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/main/java/rx/Observable.java
Original file line number Diff line number Diff line change
Expand Up @@ -1189,6 +1189,44 @@ public final static <T> Observable<T> from(T[] array) {
return from(Arrays.asList(array));
}

/**
* Converts an String into an Observable that emits the chars in the String.
* <p>
* <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.png" alt="">
* <dl>
* <dt><b>Scheduler:</b></dt>
* <dd>{@code from} does not operate by default on a particular {@link Scheduler}.</dd>
* </dl>
*
* @param str
* the source String
* @return an Observable that emits each char in the source String
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Creating-Observables#from">RxJava wiki: from</a>
*/
public final static Observable<String> from(final String str) {
return Observable.create(new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
// Start emitting token's char
for (Character c : str.toCharArray()) {
subscriber.onNext(c.toString());
}

// Notify on completed
if (!subscriber.isUnsubscribed()) {
subscriber.onCompleted();
}
} catch (Throwable t) {
// Notify on error
if (!subscriber.isUnsubscribed()) {
subscriber.onError(t);
}
}
}
});
}

/**
* Returns an Observable that emits a sequential number every specified interval of time.
* <p>
Expand Down
9 changes: 9 additions & 0 deletions src/test/java/rx/ObservableTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,15 @@ public void fromArityArgs1() {
assertEquals("one", items.takeLast(1).toBlocking().single());
}

@Test
public void fromString(){
String foo = "foo";

assertEquals("f", Observable.from(foo).first().toBlocking().single());
assertEquals("o", Observable.from(foo).skip(1).take(1).toBlocking().single());
assertEquals("o", Observable.from(foo).takeLast(1).toBlocking().single());
}

@Test
public void testCreate() {

Expand Down