It seems that it is currently impossible to create an Observable from an array of primitives, e.g.:
char[] chars = "some string".toCharArray();
Observable.from(chars); //does not compile
Is this a conscious decision?
Could not you just use Observable.from(Arrays.asList(chars)) ?
There's a gotcha with this approach. Arrays.asList(chars) will return a one-element list containing char array chars instead of list of characters from chars. So it's not what I'd hope for and I can't use it with Observable the way I'd like to.
I can use third-party library, like Guava and have Chars.asList(chars), but I'd prefer to avoid having such dependency.
We named it just.
A proper support would require specializing RxJava types to primitive types which is quite cumbersome for minimal benefit.
I probably didn't make myself clear. I'd like to have an option to observe a sequence of characters in a String, so that:
char[] chars = "some string".toCharArray();
Observable.from(chars).subscribe(curr -> System.out.println("next: " + curr)); //currently does not compile
outputs:
next: s
next: o
next: m
next: e
next:
next: s
next: t
next: r
next: i
next: n
next: g
The options you mentioned work the following way:
Observable.from(Arrays.asList(chars)).subscribe(curr -> System.out.println("next: " + curr));
outputs:
next: [C@6193b845
and the same for the other case
Observable.just(chars).subscribe(curr -> System.out.println("next: " + curr));
outputs:
next: [C@1f17ae12
char[] chars = "string".toCharArray();
Observable.range(0, chars.length).map(i -> chars[i]).subscribe(...)
@akarnokd I can understand it as long as it's a conscious decision. Note however that without this support it's easy to fall for a trap, such as:
Observable.from(Arrays.asList(chars))
which as described above does not do what might seem most intuitive.
In Java typically you'll have many overloads of methods accepting array of primitive types, e.g.
Arrays.copyOf(T[] original, int newLength)
Arrays.copyOf(boolean[] original, int newLength)
Arrays.copyOf(byte[] original, int newLength)
Arrays.copyOf(char[] original, int newLength)
//and others
@akarnokd regarding your example - sure, it's doable, I'm just asking to facilitate usage.
Such source factory methods doesn't have to be on the Observable itself so you can have your own class with from in it. You can take the OnSubscribeFromArray implementation of #3477 and change the array type at your leisure.
Another way to do it:
Observable.fromArray("string".split("")).map(s -> s.charAt(0)).subscribe(...)
Most helpful comment