What is the best practice for managing subscriptions in RxScala?

69 views Asked by At

I want to control the scope for my subscriptions and even in the presence of exceptions while avoiding using var for my subscriptions

In Rx/F# I would do this

use subscription = Observable.subscribe ...

and the subscription is automatically disposed when leaving the scope.

What is the best practice in Scala?

1

There are 1 answers

0
vidi On BEST ANSWER

My solution is to use scala-arm but I'm not sure if there is a better way to do it.

I added an implicit conversion from Subscription to Resource and used managed resource mechanism from scala-arm like this:

object ResourceImplicits {
  implicit val subscription2Resource = new Resource[Subscription] {
    override def close(s: Subscription): Unit = s.unsubscribe()  }
}

//...

for (s <- managed(obs.subscribe { n => println(s"n=$n")})) {
    // the subscription is alive in this scope
    // ...
}
//the subscription has been unsubscribed