Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional listener with state

Let's say in my pure Scala program i have a dependency to a Java service. This Java service accepts a listener to notify me when some data changes.

Let's say the data is a tuple(x, y) and the java service calls the listener whenever X or Y changes but i'm interested only when X.

For this my listener has to save the last value of X, and forward the update/call only when oldX != X, so in order to have this my impure scala listener implementation has to hold a var oldX

val listener = new JavaServiceListener() {

 var oldX;
 def updated(val x, val y): Unit = {
  if (oldX != x) {
     oldX = x
    //do stuff
  }
}

javaService.register(listener)

How would i go about to design a wrapper for this kind of thing in Scala without val or mutable collections ? I can't at the JavaServiceListener level since i'm bound by the method signature, so I need another layer above which the java listener forwards to somehow

like image 388
AdrianS Avatar asked Jun 27 '18 08:06

AdrianS


1 Answers

My preference would be to wrap it in a Monix Observable, then you can use distinctUntilChanged to eliminate consecutive duplicates. Something like:

import monix.reactive._

val observable = Observable.create(OverflowStrategy.Fail(10)){(sync) =>
    val listener = new JavaServiceListener() {
      def updated(val x, val y): Unit = {
        sync.onNext(x)
      }
    }

    javaService.register(listener)
    Cancelable{() => javaService.unregister(listener)}
  }

val distinctObservable = observable.distinctUntilChanged

Reactive programming allows you to use a pure model while the library handles all the difficult stuff.

like image 190
Karl Bielefeldt Avatar answered Sep 23 '22 12:09

Karl Bielefeldt