/
child_module.dart
111 lines (94 loc) · 2.44 KB
/
child_module.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
109
110
111
import 'package:flutter/widgets.dart';
import '../../flutter_modular.dart';
import '../routers/router.dart';
abstract class ChildModule {
List<Bind> _binds;
List<Bind> get binds;
List<ModularRouter> get routers;
ChildModule() {
_binds = binds;
}
void changeBinds(List<Bind> b) {
_binds = b;
}
final List<String> paths = <String>[];
final Map<Type, dynamic> _singletonBinds = {};
T getBind<T>(Map<String, dynamic> params, {List<Type> typesInRequest}) {
T bindValue;
var type = _getInjectType<T>();
if (_singletonBinds.containsKey(type)) {
bindValue = _singletonBinds[type];
return bindValue;
}
var bind = _binds.firstWhere((b) => b.inject is T Function(Inject),
orElse: () => null);
if (bind == null) {
typesInRequest.remove(type);
return null;
}
if (typesInRequest.contains(type)) {
throw ModularError('''
Recursive calls detected. This can cause StackOverflow.
Check the Binds of the $runtimeType module:
***
${typesInRequest.join('\n')}
***
''');
} else {
typesInRequest.add(type);
}
bindValue =
bind.inject(Inject(params: params, typesInRequest: typesInRequest));
if (bind.singleton) {
_singletonBinds[type] = bindValue;
}
typesInRequest.remove(type);
return bindValue;
}
/// Dispose bind from the memory
bool remove<T>() {
final type = _getInjectType<T>();
if (_singletonBinds.containsKey(type)) {
var inject = _singletonBinds[type];
_callDispose(inject);
_singletonBinds.remove(type);
return true;
} else {
return false;
}
}
_callDispose(dynamic bind) {
if (bind is Disposable || bind is ChangeNotifier) {
bind.dispose();
return;
} else if (bind is Sink) {
bind.close();
return;
}
}
/// Dispose all bind from the memory
void cleanInjects() {
for (final key in _singletonBinds.keys) {
var _bind = _singletonBinds[key];
_callDispose(_bind);
}
_singletonBinds.clear();
}
Type _getInjectType<B>() {
for (final value in _singletonBinds.values) {
if (value is B) {
return value.runtimeType;
}
}
return B;
}
/// Create a instance of all binds isn't lazy Loaded
void instance() {
for (final bindElement in _binds) {
if (!bindElement.lazy) {
var b = bindElement.inject(Inject());
_singletonBinds[b.runtimeType] = b;
}
}
}
}