0

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.

Emre Aktürk
  • 3,306
  • 2
  • 18
  • 30

1 Answers1

3

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);
akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • I got it, Something is niggling my mind. With PublishSubject i can iterate less which makes it faster? – Emre Aktürk Feb 01 '18 at 19:57
  • Depends on what you have written and how do you measure it as "faster". – akarnokd Feb 01 '18 at 19:58
  • Doing for-loops in Java and not in RxJava has always lower overhead. I use a scrabble benchmark to measure stream processing libraries and you can get as 4x more overhead with RxJava compared to a plain for loop when everything is synchronous. – akarnokd Feb 01 '18 at 20:01
  • You are right. I also wants to write a code that easy to read. Its a trade-off. I will stick with range. Thanks – Emre Aktürk Feb 01 '18 at 20:05