This repository has been archived by the owner on Jan 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.dart
108 lines (90 loc) · 2.64 KB
/
runner.dart
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import 'package:codenic_bloc_use_case/src/base.dart';
import 'package:codenic_bloc_use_case/src/util/ensure_async.dart';
import 'package:equatable/equatable.dart';
import 'package:fpdart/fpdart.dart';
import 'package:meta/meta.dart';
part 'runner_state.dart';
/// {@template Runner}
///
/// An abstract use case for executing tasks asynchronously via a cubit which
/// accepts a [P] parameter and emits either an [L] failed value or an [R]
/// success value.
///
/// {@endtemplate}
abstract class Runner<P, L, R> extends DistinctCubit<RunnerState>
with BaseUseCase<P, L, R> {
/// {@macro Runner}
Runner() : super(const RunnerInitial(DistinctCubit.initialActionToken));
/// The latest value emitted by calling [run] which can either reference the
/// [leftValue] or the [rightValue].
///
/// This can be used to determine which is latest among the two values.
///
/// If [run] has not been called even once, then this is `null`.
@override
Either<L, R>? get value => super.value;
/// {@template Runner.leftValue}
///
/// The last error value emitted by calling [run].
///
/// If [run] has not failed even once, then this is `null`.
///
/// {@endtemplate}
@override
L? get leftValue => super.leftValue;
/// {@template Runner.rightValue}
///
/// The last success value emitted by calling [run].
///
/// If [run] has not succeeded even once, then this is `null`.
///
/// {@endtemplate}
@override
R? get rightValue => super.rightValue;
/// The use case action callback called on [run].
@protected
@override
Future<Either<L, R>> onCall(P params);
/// Executes the [onCall] use case action.
///
/// This will initially emit a [Running] state followed either by a
/// [RunFailed] or [RunSuccess].
Future<void> run({required P params}) async {
final actionToken = requestNewActionToken();
await ensureAsync();
if (isClosed) return;
if (distinctEmit(
actionToken,
() => Running(actionToken),
) ==
null) {
return;
}
final result = await onCall(params);
if (isClosed) return;
distinctEmit(
actionToken,
() {
setParamsAndValue(params, result);
return result.fold(
(l) => RunFailed(l, actionToken),
(r) => RunSuccess(r, actionToken),
);
},
);
}
/// Clears all the data then emits a [RunnerInitial].
@override
Future<void> reset() async {
final actionToken = requestNewActionToken();
await ensureAsync();
if (isClosed) return;
distinctEmit(
actionToken,
() {
super.reset();
return RunnerInitial(actionToken);
},
);
}
}