How to build an Observable out of individual computation steps with RxScala/RxJava?

28 views Asked by At

I currently have the following code:

def method(): Future[State] = Future {
  // some processing
  State.Completed
}

But now I've noticed that I actually want to "publish" a set of intermediate states instead:

def method(): Observable[State] = ? {
  // some processing
  publish State.State1
  // some processing
  publish State.State2
  // some processing
  publish State.Completed
}

Is there an easy way of achieving this? Although I've described this as 3 state transitions, it could actually happen that I may be going through more transitions or less. I would like the change from Future to Observable to imply the least amount of changes from my current "imperative" code.

Also, I would like these "events" to be published in realtime, and not just when returning from the method.

1

There are 1 answers

0
akarnokd On BEST ANSWER

Use Observable.create and just push the next state whenever:

Observable<State> stateSource = Observable.create(emitter -> {
     // some processing
     emitter.onNext(State.State1);

     // some processing
     emitter.onNext(State.State2);

     // some processing
     emitter.onNext(State.Completed);

     // no further state changes
     emitter.onComplete();
});