简体   繁体   中英

How to make Observable that emit character after 1 second of time interval

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM