If you have a Stream
of Integer
only then you can simply do:
Observable.fromIterable(IntStream.rangeClosed(from,to)
.boxed()
.collect(Collectors.toList()));
Arguments for rangedClosed
are inclusive.
There is another general method that you can use which is closer to what you have in your attempt:
Observable.fromIterable(Stream.iterate(from, integer -> integer + 1)
.filter(integer -> integer < (to+1))
.limit((long(to+1)-long(from))
.collect(Collectors.toList()));
EDIT1
If you want an infinite stream. Java Stream's generate
and iterate
both produce infinite streams. In my example using iterate
(you can replace it using generate
with a Supplier
where you have your custom object creation code) and get rid of all the terminal operators like limit
.
Then wrap them into an Observable
or into a Flowable
and then into an Observable
if you want backpressure support with RxJava2.
Like this:
Observable.just(Stream.generate(() -> // Object creation logic here));
Or
Observable.just(Flowable.just(Stream.generate(() -> // Object creation logic here)));
Keep in mind that if you do this then your code will keep creating objects indefinitely and your program will run until your memory runs out.
I guess you have some kind of service that is sending you data and you need to make some transformation and send that data as a stream somewhere else. I would recommend getting the data as a Future
and then wrapping it into a Flowable
and then streaming the data to wherever you are sending it.
Like:
Flowable.fromFuture(senderService.getDataAsCompletableFuture);
And then specify a backpressure strategy.
EDIT2
You can use Observable.generate()
to do it.
Like:
Observable.generate(() -> from, (value, emitter) -> {
emitter.onNext(value);
return value + 1;
});