- Notifications
You must be signed in to change notification settings - Fork94
/
Copy pathtask_either.go
56 lines (46 loc) · 1.54 KB
/
task_either.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package mo
// NewTaskEither instanciates a new TaskEither.
funcNewTaskEither[Rany](fff0[R])TaskEither[R] {
returnTaskEither[R]{NewTask[R](f)}
}
// NewTaskEitherFromIO instanciates a new TaskEither from an existing IO.
funcNewTaskEitherFromIO[Rany](ioIO[R])TaskEither[R] {
returnTaskEither[R]{NewTaskFromIO[R](io)}
}
// TaskEither represents a non-deterministic asynchronous computation that
// can cause side effects, yields a value of type `R` and can fail.
typeTaskEither[Rany]struct {
Task[R]
}
// OrElse returns value if task succeeded or default value.
func (tTaskEither[R])OrElse(fallbackR)R {
either:=t.Run().Either()
right,isRight:=either.Right()
if!isRight {
returnfallback
}
returnright
}
// Match executes the first function if task succeeded and second function if task failed.
// It returns a new Option.
func (tTaskEither[R])Match(onLeftfunc(error)Either[error,R],onRightfunc(R)Either[error,R])Either[error,R] {
either:=t.Run().Either()
returneither.Match(onLeft,onRight)
}
// TryCatch is an alias to Match
func (tTaskEither[R])TryCatch(onLeftfunc(error)Either[error,R],onRightfunc(R)Either[error,R])Either[error,R] {
returnt.Match(onLeft,onRight)
}
// ToTask converts TaskEither to Task
func (tTaskEither[R])ToTask(fallbackR)Task[R] {
returnNewTask(func()*Future[R] {
returnt.Run().
Catch(func(errerror) (R,error) {
returnfallback,nil
})
})
}
// ToEither converts TaskEither to Either.
func (tTaskEither[R])ToEither()Either[error,R] {
returnt.Run().Either()
}