Merge pull request #4 from KlimYarosh/master

Add parameter to provider
This commit is contained in:
Sergey Penkovsky
2023-01-04 11:09:47 +03:00
committed by GitHub
3 changed files with 66 additions and 19 deletions

View File

@@ -28,9 +28,11 @@ class FeatureModule extends Module {
),
)
.singleton();
bind<DataBloc>().toProvide(
() => DataBloc(
bind<DataBloc>().toProvideWithParams(
(param) => DataBloc(
currentScope.resolve<DataRepository>(named: 'networkRepo'),
param,
),
);
}
@@ -45,7 +47,7 @@ void main() async {
.openSubScope('featureScope')
.installModules([FeatureModule(isMock: true)]);
final dataBloc = subScope.resolve<DataBloc>();
final dataBloc = subScope.resolve<DataBloc>(params: 'PARAMETER');
dataBloc.data.listen((d) => print('Received data: $d'),
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
@@ -58,11 +60,13 @@ class DataBloc {
Stream<String> get data => _dataController.stream;
final StreamController<String> _dataController = StreamController.broadcast();
DataBloc(this._dataRepository);
final String param;
DataBloc(this._dataRepository, this.param);
Future<void> fetchData() async {
try {
_dataController.sink.add(await _dataRepository.getData());
_dataController.sink.add(await _dataRepository.getData(param));
} catch (e) {
_dataController.sink.addError(e);
}
@@ -74,7 +78,7 @@ class DataBloc {
}
abstract class DataRepository {
Future<String> getData();
Future<String> getData(String param);
}
class NetworkDataRepository implements DataRepository {
@@ -84,26 +88,42 @@ class NetworkDataRepository implements DataRepository {
NetworkDataRepository(this._apiClient);
@override
Future<String> getData() async => await _apiClient.sendRequest(
url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
Future<String> getData(String param) async => await _apiClient.sendRequest(
url: 'www.google.com',
token: _token,
requestBody: {'type': 'data'},
param: param);
}
abstract class ApiClient {
Future sendRequest({@required String url, String token, Map requestBody});
Future sendRequest({
@required String url,
String token,
Map requestBody,
String param,
});
}
class ApiClientMock implements ApiClient {
@override
Future sendRequest(
{@required String? url, String? token, Map? requestBody}) async {
return 'Local Data';
Future sendRequest({
@required String? url,
String? token,
Map? requestBody,
String? param,
}) async {
return 'Local Data $param';
}
}
class ApiClientImpl implements ApiClient {
@override
Future sendRequest(
{@required String? url, String? token, Map? requestBody}) async {
return 'Network data';
Future sendRequest({
@required String? url,
String? token,
Map? requestBody,
String? param,
}) async {
return 'Network data $param';
}
}

View File

@@ -11,7 +11,9 @@
/// limitations under the License.
///
enum Mode { SIMPLE, INSTANCE, PROVIDER_INSTANCE }
enum Mode { SIMPLE, INSTANCE, PROVIDER_INSTANCE, PROVIDER_WITH_PARAMS_INSTANCE }
typedef ProviderWithParams<T> = T Function(dynamic params);
/// RU: Класс Binding<T> настраивает параметры экземпляра.
/// ENG: The Binding<T> class configures the settings for the instance.
@@ -22,6 +24,7 @@ class Binding<T> {
late String _name;
T? _instance;
T? Function()? _provider;
ProviderWithParams<T>? _providerWithParams;
late bool _isSingleton = false;
late bool _isNamed = false;
@@ -91,6 +94,16 @@ class Binding<T> {
return this;
}
/// RU: Инициализация экземляпяра  через провайдер [value] c динамическим параметром.
/// ENG: Initialization instance via provider [value] with a dynamic param.
///
/// return [Binding]
Binding<T> toProvideWithParams(ProviderWithParams<T> value) {
_mode = Mode.PROVIDER_WITH_PARAMS_INSTANCE;
_providerWithParams = value;
return this;
}
/// RU: Инициализация экземляпяра  как сингелтон [value].
/// ENG: Initialization instance as a singelton [value].
///
@@ -117,4 +130,13 @@ class Binding<T> {
}
return _provider?.call();
}
/// RU: Поиск экземпляра с параметром.
///
/// ENG: Resolve instance with [params].
///
/// return [T]
T? providerWithParams(dynamic params) {
return _providerWithParams?.call(params);
}
}

View File

@@ -86,8 +86,8 @@ class Scope {
/// If you want to get [null] if the dependency cannot be found then use [tryResolve] instead
/// return - returns an object of type [T] or [StateError]
///
T resolve<T>({String? named}) {
var resolved = tryResolve<T>(named: named);
T resolve<T>({String? named, dynamic params}) {
var resolved = tryResolve<T>(named: named, params: params);
if (resolved != null) {
return resolved;
} else {
@@ -99,7 +99,7 @@ class Scope {
/// RU: Возвращает найденную зависимость типа [T] или null, если она не может быть найдена.
/// ENG: Returns found dependency of type [T] or null if it cannot be found.
///
T? tryResolve<T>({String? named}) {
T? tryResolve<T>({String? named, dynamic params}) {
// 1 Поиск зависимости по всем модулям текущего скоупа
if (_modulesList.isNotEmpty) {
for (var module in _modulesList) {
@@ -112,6 +112,11 @@ class Scope {
return binding.instance;
case Mode.PROVIDER_INSTANCE:
return binding.provider;
case Mode.PROVIDER_WITH_PARAMS_INSTANCE:
if (params == null) {
throw StateError('Param is null. Maybe you forget pass it');
}
return binding.providerWithParams(params);
default:
return null;
}