async_lite 1.0.0
async_lite: ^1.0.0 copied to clipboard
Lightweight version of the popular package
// ignore_for_file: avoid_print
import 'package:async_lite/async_lite.dart';
void main() async {
// Example 1: Using LazyFutureExt to cache async calls
print('--- LazyFutureExt Example ---');
// Multiple parallel calls return the same cached result
final futures = List.generate(5, (i) => fetchData.byLazy());
final results = await Future.wait(futures);
for (var i = 0; i < results.length; i++) {
print('Call $i: ${results[i]}');
}
// Example 2: Using Result type
print('\n--- Result Example ---');
final success = await handleOperation(true);
print(success);
final failure = await handleOperation(false);
print(failure);
// Example 3: Using AsyncCache
print('\n--- AsyncCache Example ---');
final cache = AsyncCache<String>(const Duration(seconds: 2));
final cached1 = await cache.fetch(expensiveOperation);
print('First: $cached1');
final cached2 = await cache.fetch(expensiveOperation);
print('Second (cached): $cached2');
// Example 4: UI State from Result
print('\n--- UI State Example ---');
final successState = (await handleOperation(true)).toUiState();
handleUiState(successState);
final errorState = (await handleOperation(false)).toUiState();
handleUiState(errorState);
}
Future<String> fetchData() async {
await Future.delayed(const Duration(milliseconds: 500));
return 'Data loaded at ${DateTime.now()}';
}
Future<Result<String>> handleOperation(bool success) async {
if (success) {
return const ValueResult('Operation completed');
}
return const ErrorResult('Operation failed');
}
Future<String> expensiveOperation() async {
await Future.delayed(const Duration(seconds: 1));
return 'Expensive result: ${DateTime.now()}';
}
void handleUiState<T>(BaseUiState<T> state) {
switch (state.type) {
case UiState.loading:
print('Loading...');
case UiState.value:
print('Success: ${state.valueOrNull}');
case UiState.error:
print('Error: ${state.messageOrNull}');
}
}