1

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.

devoured elysium
  • 101,373
  • 131
  • 340
  • 557

1 Answers1

1

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();
});
akarnokd
  • 69,132
  • 14
  • 157
  • 192