scala - Filtering inside for-comprehension with futures -
i doing this:
(for { data <- future(getdata) updated = makechanges(data) if updated != data _ <- future(saveupdates(updated)) _ <- future(recordtransaction) } yield ()).recover { case e: nosuchelementexception => () }
when filter not satisfied, skips remaining 2 steps (good!) throwing exception (not good), have catch , handle @ end. using exceptions flow control not feel elegant me though, wondering if there better way this, aside obvious - wrapping remaining lines if statement:
_ <- if(updated != data) future(saveupdates(updated)) else future.successful(()) _ <- if(updated != data) ...
i don't think can avoid exception flow control using comprehension in way, use nested expression instead of filter , handle condition manually giving scala return type needs in case condition not satisfied:
for { data <- future(data) updated = makechanges(data) res = { if (updated != data) future.successful(()) else { _ <- future(saveupdates(updated)) _ <- future(recordtransaction) } yield () } } yield res
but example i'd go simple way , drop comprehension results in more readable code (probably real use case more complex though):
future(data).flatmap(d => { val updated = makechanges(d) if(updated == d) future.successful(()) else future(saveupdates(updated)).map(_ => recordtransaction) })
Comments
Post a Comment