OutWatch: enforce changes on Elements to be shown immediately

162 Views Asked by At

I want to have a loading spinner that can be used from everywhere. So I created a BoolHandler:

val loadingSpinnerEvents = createBoolHandler()

Which is bound to the loading spinner div:

val loadingSpinner = div(
  hidden <-- loadingSpinnerEvents
  , Icon.loadingIcon
)

So I do the following:

def reducer(previousState: State, action: Action): State = {
  var st = previousState
  loadingSpinnerEvents <-- Observable.create { obs =>
    obs.next(false)
    st = newState(previousState, action)
    Future {
    // do the long running work

    }.onComplete { _ =>
      obs.next(true)
      obs.complete()
    }
  }
  st
}

According to println output, the boolean values are handled correctly and immediately.

The problem is that element changes are shown only after the whole work is done.

Is there a way to enforce that or do I miss something.

1

There are 1 best solutions below

2
On

One solution would be to create an Observable that starts with false, and then does some of the work and turns to true. I.e.

val loadingSpinnerEvents = Observable.create{ obs =>
  obs.next(false)
  //do some work here
  obs.next(true)
}

However this depends on the work being done. If it's synchronous, this approach should work fairly well.

If your work is asynchronous and takes a callback, you can also wrap it in an Observable:

val loadingSpinnerEvents = Observable.create{ obs => 
  obs.next(false)
  // do work with callback
  doWork {
    obs.next(true)
    obs.complete()
  }
}