async_field 1.1.4
async_field: ^1.1.4 copied to clipboard
Async fields that can be stored or fetched from any source (databases, web services, local storage or other thread/isolate), with observable values, caches and stale versions.
async_field #
Async fields that can be stored or fetched from any source (databases, web services, local storage or other thread/isolate), with observable values, caches and stale versions.
Usage #
A simple usage example:
import 'dart:convert' as convert;
import 'dart:io';
import 'package:async_field/async_field.dart';
void main() async {
// The fields storage:
var storage = AsyncStorage();
// Get field 'btc_usd',
var field = storage.getField<double>('btc_usd')
..defaultValue = double.nan // default value (before fetch).
..withFetcher(_fetchBtcUsd) // the field fetcher.
..onChange.listen((field) => print('onChange> $field')); // change listener.
print('BTC-USD: $field');
print('field.info: ${field.info}');
// Get the field value:
var btcUsd = await field.get();
print('field.get(): $btcUsd');
print('BTC-USD: $field');
print('field.info: ${field.info}');
}
/// Function that fetches the BTC-USD spot price (Coinbase public API).
Future<double> _fetchBtcUsd(AsyncField<double> field) async {
return _getURL('https://api.coinbase.com/v2/prices/BTC-USD/spot')
.resolveMapped((body) {
var json = convert.json.decode(body) as Map<String, dynamic>;
var amount = json['data']['amount'];
return double.parse('$amount');
});
}
/// Simple HTTP get URL function.
Future<String> _getURL(String url) async {
var uri = Uri.parse(url);
var httpClient = HttpClient();
try {
var response = await httpClient
.getUrl(uri)
.then((request) => request.close());
if (response.statusCode != 200) {
throw HttpException('HTTP ${response.statusCode}', uri: uri);
}
return await response.transform(convert.utf8.decoder).join();
} finally {
httpClient.close();
}
}
OUTPUT:
BTC-USD: NaN
field.info: { "id": "btc_usd" , "storage": 1 }
field.get(): 76879.455
BTC-USD: 76879.455
field.info: { "value": 76879.455 , "id": "btc_usd" , "valueTime": 1793767610222 , "storage": 1 }
onChange> 76879.455
Source #
The official source code is hosted @ GitHub:
Features and bugs #
Please file feature requests and bugs at the issue tracker.
Contribution #
Any help from the open-source community is always welcome and needed:
- Found an issue?
- Please fill a bug report with details.
- Wish a feature?
- Open a feature request with use cases.
- Are you using and liking the project?
- Promote the project: create an article, do a post or make a donation.
- Are you a developer?
- Fix a bug and send a pull request.
- Implement a new feature.
- Improve the Unit Tests.
- Have you already helped in any way?
- Many thanks from me, the contributors and everybody that uses this project!
If you donate 1 hour of your time, you can contribute a lot, because others will do the same, just be part and start with your 1 hour.
Author #
Graciliano M. Passos: gmpassos@GitHub.