Search code examples
scalaobservablemonix

Better way to handle errors with Monix Observable


I am trying to build reactive application with monix 3.0.0-RC1.

For instance a have a Seq of Int's, and the second element is wrong. I can use Oservable.raiseError(...) to handle this:

  Observable.fromIterable(Seq(1,2,3))
    .flatMap( i =>
      if (i == 2) Observable.raiseError(new Exception("Wrong i"))
      else Observable.pure(i)
    )
    .doOnNext(i => println(s"Processing $i"))
    .foreachL(i => println(s"Finished $i"))
    .onErrorHandle(_ => Task.unit)

I do not like thrown exception in the code above.

In the other hand I can use Scala's Either:

Observable.fromIterable(Seq(1,2,3))
  .map( i =>
    if (i == 2) Left("Wrong i")
    else Right(i)
  )
  .doOnNext(either => either.map( i => println(s"Processing $i") ))
  .foreachL(either => either.map( i => println(s"Finished $i") ))

But either => either.map(...) in every step in not cool.

What is the better way to handle errors?


Solution

  • You can use collect if you only care about the right result, e.g.

    val logError = {
      case Right(_) => Task.unit
      case Left(i) => Task.delay(println(s"An error occured $i"))
    }
    
    Observable.fromIterable(Seq(1,2,3))
      .map( i =>
        if (i == 2) Left("Wrong i")
        else Right(i)
      )
      .doOnNext(logError)
      .collect {
        case Right(value) => value
      }
      .foreachL(i => println(i))