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 wha
Solution 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
Solution 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.
Post a Comment for "How To Make Observable That Emit Character After 1 Second Of Time Interval"