Emre Aktürk
Emre Aktürk

Reputation: 3346

For-loop with RxJava2 or RxKotlin

I want to build a async operation that iterates chars in given string. I have a char array taken by "mystring".toCharArray(). I want to iterate each 10th character by using RX.

I know i can do it with AsyncTask and for-loops but i thought RX would be more elegant solution. I have read documentations but did not recognize how to do it.

Another idea in my mind to create a PublishSubject and fire onNext() in a for-loop that index increments by 10 with subscription.

PS: "mystring" can be much more larger like a json, xml or etc. Please feel free to comment about ram profiling.

Upvotes: 0

Views: 538

Answers (1)

akarnokd
akarnokd

Reputation: 70017

RxJava doesn't support primitive arrays, but you can use a for loop in the form of the range operator and index into a primitive array. With some index arithmetic, you can get every 10th character easily:

char[] chars = ...

Observable.range(0, chars.length)
    .filter(idx -> idx % 10 == 0)
    .map(idx -> chars[idx])
    .subscribe(System.out::println);

Upvotes: 3

Related Questions