Skip to content

Commit 58fb3fd

Browse files
committed
add finallyDo to helper functions
1 parent e7bbca3 commit 58fb3fd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/ConcurrentTask.elm

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ module ConcurrentTask exposing
99
, batch, sequence
1010
, map, andMap, map2, map3, map4, map5
1111
, attempt, Response(..), UnexpectedError(..), onProgress, Pool, pool
12+
, finallyDo
1213
)
1314

1415
{-| A Task similar to `elm/core`'s `Task` but:
@@ -708,6 +709,40 @@ debugLog tag message =
708709
}
709710

710711

712+
{-| Always executes the Task, regardless of whether the previous Task has succeeded or failed.
713+
714+
The behavior is similar to JavaScript's `finally` block in a `try-catch-finally` statement.
715+
716+
This can, for example, be used to ensure that a resource is always released after being locked:
717+
718+
import ConcurrentTask exposing (ConcurrentTask)
719+
720+
lockResource : ConcurrentTask String ()
721+
lockResource =
722+
succeed ()
723+
724+
unlockResource : ConcurrentTask String ()
725+
unlockResource =
726+
succeed ()
727+
728+
performOperation : ConcurrentTask String ()
729+
performOperation =
730+
fail "operation failed"
731+
732+
secureOperation : ConcurrentTask String ()
733+
secureOperation =
734+
lockResource
735+
|> andThenDo performOperation
736+
|> finallyDo unlockResource
737+
738+
-}
739+
finallyDo : ConcurrentTask x a -> ConcurrentTask x b -> ConcurrentTask x a
740+
finallyDo t2 t1 =
741+
t1
742+
|> onError (\e -> t2 |> andThenDo (fail e))
743+
|> andThenDo t2
744+
745+
711746

712747
-- Batch Helpers
713748

0 commit comments

Comments
 (0)