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?
Observable.raiseError(...)
withObservable.empty
or even changeflatMap
tofilter
. Well,either => ...
can be replaced by_.foreach( i => println(s"Processing $i"))
or byfor (i <- _) println(s"Finished $i")
, especially by-products effects in the map are wrong, especially if only side effects are needed. - extrnObservable.empty
looks good, thanks. - Oleg