I am trying to write a reactive application with Monix 3.0.0-RC1.

Suppose I have a sequence of numbers in which the second element is not correct. I can use Oservable.raiseError(...) to handle this case:

  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) 

But here I don’t really like that the exception is thrown.

On the other hand, I can use Skalovsky 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 to write every time either => either.map(...) also not cool.

Is there a better way to handle errors in such cases?

  • It is not entirely clear what result you are trying to achieve. In the first example, an error in one value terminates all calculations, in the second, in fact, it simply skips the wrong element. If necessary, you can replace Observable.raiseError(...) with Observable.empty or even change flatMap to filter . Well, either => ... can be replaced by _.foreach( i => println(s"Processing $i")) or by for (i <- _) println(s"Finished $i") , especially by-products effects in the map are wrong, especially if only side effects are needed. - extrn
  • The idea of ​​replacing it with Observable.empty looks good, thanks. - Oleg

0