getItem method

  1. @override
Future<Result<int, String, T?>> getItem({
  1. String? id,
  2. Future<Result<int, String, T?>> alternativeFunc()?,
  3. dynamic docRef,
  4. String channel = 'main',
  5. CrudStrategy strategy = const DefaultCrudStrategy(),
})
override

Implementation

@override
Future<Result<int, String, T?>> getItem({
  String? id,
  Future<Result<int, String, T?>> Function()? alternativeFunc,
  dynamic docRef,
  String channel = 'main',
  CrudStrategy strategy = const DefaultCrudStrategy(),
}) async {
  // Emit null first if the strategy requires it.
  if (strategy.pushNullFirst) {
    _getResultStream(channel).add(_nullResult);
    _getItemStream(channel).add(null);
  }
  // Return cached item if available and forceUpdate is not required.
  final cachedItems = _currentList(channel);
  if (!strategy.forceUpdate && cachedItems.isNotEmpty) {
    final item = cachedItems.cast<T?>().firstWhere((e) => e?.id == id, orElse: () => null);
    if (item != null) {
      _getItemStream(channel).add(item);
      final list = _updatedList(channel, item);
      _getItemsStream(channel).add(list);
      final foundResult = _dataResult(item);
      _getResultStream(channel).add(foundResult);
      return foundResult;
    }
  }
  // Fetch item from the remote source.
  final res = await (alternativeFunc != null
      ? alternativeFunc()
      : _crud.getItem(id: id, docRef: docRef));
  if (res.code == 0) {
    final fetchedItem = res.data!;
    _getItemStream(channel).add(fetchedItem);
    final list = _updatedList(channel, fetchedItem);
    _getItemsStream(channel).add(list);
  }
  _getResultStream(channel).add(res);
  return res;
}