2

Since I'm quite new to Reactive Extensions, I was curious about the following things.

By using Rx in Scala, I want to be able to call a method that retrieves content from an API every second.

So far, I've taken a look at the creational operators used within Rx such as Interval, Timer and so forth. But unfortunately, I cannot come up with the correct solution.

Does anyone have some experience with this, and preferably code examples to share?

Thanks in advance!

Malt
  • 28,965
  • 9
  • 65
  • 105
dsafa
  • 783
  • 2
  • 8
  • 29

1 Answers1

3

Using RxJava:

Observable.interval(1, TimeUnit.SECONDS)
          .map(interval -> getSuffFromApi()) //Upto here, we have an observable the spits out the data from the API every second
          .subscribe(response-> System.out.println(response)); //Now we just subscribe to it

Or:

Observable.interval(1, TimeUnit.SECONDS) //Emit every second
          .subscribe(interval ->System.out.println(getSuffFromApi())) //onNext - get the data from the API and print it
Malt
  • 28,965
  • 9
  • 65
  • 105
  • Although this is a valid solution, the problem that I keep bouncing at is that the control flow terminates the execution even before the response arrives. Any suggestions? – dsafa Dec 01 '15 at 19:00
  • @dsafa that means that you're doing something asynchronously and not waiting for the response. My answer assumes that `getSuffFromApi()` is a blocking call and that you don't need to execute it on a different thread. Are you doing something in a different thread? Perhaps you have a `subscribeOn` / `observeOn` somewhere? – Malt Dec 01 '15 at 19:20