2

I have a long running method that I wish to be able to update something else everytime a step is concluded.

class A {

private B b;

callLongRunning() {
    b.longRunningMethod()
}


class B {

longRunningMethod(){
   doSomethingThatTakesAWhile();
   doSomethingThatTakesAWhile();
   doSomethingThatTakesAWhile();
   doSomethingThatTakesAWhile();
}

After each call to B.doSomethingThatTakesAWhile() I wish to "return" a message so class A can update a registry with some info.

I am looking as Rx.Observables but I am not understanding how to use it in this scenario.

I wish to do something like this:

class A {

private B b;

callLongRunning() {
    someSpecialStateObject.onPush(state => updateDb(state));
    someSpecialStateObject.onFinish(state => doSomethingElse(state));
    b.longRunningMethod(someSpecialStateObject)
    //continue only after it all ends
}


class B {

longRunningMethod(someSpecialStateObject){
   doSomethingThatTakesAWhile();
   someSpecialStateObject.push("finished step 1");
   doSomethingThatTakesAWhile();
   someSpecialStateObject.push("finished step 2");
   doSomethingThatTakesAWhile();
   someSpecialStateObject.push("finished step 3");
   doSomethingThatTakesAWhile();
   someSpecialStateObject.finish("finished everything");
}
Saita
  • 964
  • 11
  • 36
  • simple solution is to create a Progress class and update it after each step in the longRunningMethod(). Of course, you it can get complicated if the requirement gets finer. – Khanna111 Apr 13 '20 at 22:22
  • Yes, but is there and well known library with that kind of support? – Saita Apr 13 '20 at 22:23
  • 1
    Just use the normal Observervable class and observer interface from java. Basic example: https://www.concretepage.com/java/example-observer-observable-java – Davide Apr 13 '20 at 22:25
  • I was checking that, but it seems there is no support for "finishing" (I can notify with a particular value and break the execution, but still) and no easy way to deal with exceptions. It's very easy to end up with the execution stuck. But thank you for the suggestion, I am looking a little more into it. – Saita Apr 13 '20 at 22:30
  • https://stackoverflow.com/a/34697008/10634638 – estinamir Apr 13 '20 at 22:31

1 Answers1

2

Here is what I ended up with:

 public Observable<String> execute() {
        return Observable.create(emitter -> {
            emitter.onNext("step 1");
            doStep1();
            emitter.onNext("step 2");
            doStep2();
            emitter.onNext("All steps finished.");
            emitter.onCompleted();
        }, Emitter.BackpressureMode.LATEST);
    }
  final String[] lastMessage = {""};
  myClass.execute().toBlocking().forEach(s -> {
      log(s);
      lastMessage[0] = s;
  });
  doSomethingWithTheLastMessage(lastMessage[0]);

I just wish the emitter.onCompleted() could return a value.

Saita
  • 964
  • 11
  • 36