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?
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