-
Notifications
You must be signed in to change notification settings - Fork 437
/
EffectUsage.kt
56 lines (46 loc) · 1.38 KB
/
EffectUsage.kt
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 arrow.core.continuations
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.Dispatchers
sealed interface MyError
sealed interface SubError : MyError
sealed interface OtherError : MyError {
object Actual : OtherError
}
context(EffectScope<SubError>)
suspend fun subprogram(): Unit =
println("Hello SubProgram!")
context(EffectScope<OtherError>)
suspend fun otherprogram(): Unit =
println("Hello OtherProgram!")
context(EffectScope<OtherError>)
suspend fun fail(): MyResponse =
shift(OtherError.Actual)
fun main() =
runBlocking(Dispatchers.Default) {
effect<MyError, Unit> {
subprogram()
otherprogram()
fail()
}.fold(::println) { }
// Hello SubProgram!
// Hello OtherProgram!
// OtherError$Actual@7cd62f43
}
sealed interface MyResponse
object EmptyResponse : MyResponse
data class ErrorResponse(val error: Throwable) : MyResponse
data class BodyResponse(val body: String) : MyResponse
context(EffectScope<SubError>)
suspend fun respondWithBody(): BodyResponse =
BodyResponse("Hello Program!")
context(EffectScope<OtherError>)
suspend fun attemptOrError(): MyResponse =
ErrorResponse(RuntimeException("Oh no!"))
fun respond(): Effect<MyError, MyResponse> =
effect {
when (attemptOrError()) {
is BodyResponse -> respondWithBody()
EmptyResponse -> EmptyResponse
is ErrorResponse -> fail()
}
}