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

旧巷老猫 提交于 2020-01-04 18:31:20

问题


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.



来源:https://stackoverflow.com/questions/46787721/how-to-make-observable-that-emit-character-after-1-second-of-time-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!