-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathThunkSideEffect.cs
61 lines (50 loc) · 1.63 KB
/
ThunkSideEffect.cs
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
57
58
59
60
61
// Copyright (c) TotalSoft.
// This source code is licensed under the MIT license.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NBB.Core.Effects
{
public class Thunk
{
public class SideEffect<TResult> : ISideEffect<TResult>, IAmHandledBy<Handler<TResult>>
{
public Func<CancellationToken, Task<TResult>> ImpureFn { get; }
public SideEffect(Func<CancellationToken, Task<TResult>> impureFn)
{
ImpureFn = impureFn;
}
}
public class Handler<TResult> : ISideEffectHandler<SideEffect<TResult>, TResult>
{
public Task<TResult> Handle(SideEffect<TResult> sideEffect, CancellationToken cancellationToken = default)
{
return sideEffect.ImpureFn(cancellationToken);
}
}
public static SideEffect<TResult> From<TResult>(Func<CancellationToken, Task<TResult>> impureFn)
{
return new(impureFn);
}
public static SideEffect<TResult> From<TResult>(Func<TResult> impureFn)
{
return new(ct => Task.FromResult(impureFn()));
}
public static SideEffect<Unit> From(Func<CancellationToken, Task> impureFn)
{
return new(async ct =>
{
await impureFn(ct);
return Unit.Value;
});
}
public static SideEffect<Unit> From(Action impureFn)
{
return new(ct =>
{
impureFn();
return Task.FromResult(Unit.Value);
});
}
}
}