-->

How to make Observable that emit character after 1

2019-07-11 17:09发布

问题:

I have just started with RxJava/android and for practice and getting started I want to make observable that emits character in string every 1 second, how can I do this? Here is what I have tried so far, its just emit string at once:

Observable<String> myObservable = Observable.interval(5000L, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .just("Hello");

I want hello like this first emit H after 1 second emit E and so on

回答1:

Split String "hello" into letters "h", "e", ... "o" using flatMap().

new ArrayList<>(Arrays.asList(string.split("")))) constructs List<String> letters and Observable.fromIterable(letters) emits each letter to downstream.

Then zipWith() zips two Observables, one is letter, other is 1 second Time.

public static void main(String[] args) throws InterruptedException {

    Observable.just("Hello")
            .flatMap(string -> Observable.fromIterable(new ArrayList<>(Arrays.asList(string.split("")))))
            .zipWith(Observable.interval(0, 1, TimeUnit.SECONDS), (letter, time) -> letter)
            .subscribe(System.out::println);

    Thread.sleep(5000);
}

Prints:

H
e
l
l
o

Process finished with exit code 0


回答2:

You can zip the interval with a character-producing source, such as the StringFlowable.characters() extensions operator:

StringFlowable.characters("Hello world")
.zipWith(Flowable.interval(1000L, TimeUnit.MILLISECONDS), (a, b) -> a)
.observeOn(AndroidSchedulers.mainThread())
.blockingSubscribe(System.out::print, Throwable::printStackTrace, System.out::println);

.observeOn(AndroidSchedulers.mainThread()).just("Hello");

Note that just is a static method that returns a new independent Observable, thus calling .just() on an instance method will have nothing to do with that previous flow.