|
1 | | -import 'dart:convert'; |
2 | | -import 'dart:io'; |
3 | 1 | import 'dart:ui'; |
4 | 2 |
|
5 | 3 | import 'package:built_collection/built_collection.dart'; |
6 | | -import 'package:http/http.dart' as http; |
| 4 | +import 'package:http_client_hoc081098/http_client_hoc081098.dart'; |
7 | 5 | import 'package:meta/meta.dart'; |
| 6 | +import 'package:rxdart_ext/rxdart_ext.dart'; |
8 | 7 |
|
9 | 8 | import 'color_remote_source.dart'; |
10 | 9 |
|
11 | 10 | class ColorRemoteSourceImpl implements ColorRemoteSource { |
12 | | - final http.Client _client; |
| 11 | + final SimpleHttpClient _client; |
13 | 12 | final Uri _url; |
14 | 13 |
|
15 | 14 | BuiltMap<String, Color>? _cachedColors; |
16 | 15 |
|
17 | 16 | ColorRemoteSourceImpl(this._client, this._url); |
18 | 17 |
|
19 | 18 | @override |
20 | | - Future<BuiltMap<String, Color>> getColors() async { |
21 | | - if (_cachedColors != null) { |
22 | | - return _cachedColors!; |
23 | | - } |
24 | | - |
25 | | - final response = await _client.get(_url); |
26 | | - |
27 | | - if (response.statusCode != HttpStatus.ok) { |
28 | | - throw HttpException( |
29 | | - 'Get colors failed failed with status code: ${response.statusCode}', |
30 | | - uri: _url, |
31 | | - ); |
32 | | - } |
33 | | - |
34 | | - return _cachedColors = |
35 | | - ((jsonDecode(response.body) as Map).map((key, value) { |
36 | | - final color = value['color']; |
37 | | - return MapEntry( |
38 | | - key as String, |
39 | | - color is String ? colorFromHex(color) : null, |
40 | | - ); |
41 | | - }) |
42 | | - ..removeWhere((key, value) => value == null)) |
43 | | - .cast<String, Color>() |
44 | | - .build(); |
| 19 | + Single<BuiltMap<String, Color>> getColors() { |
| 20 | + return Single.defer(() { |
| 21 | + if (_cachedColors != null) { |
| 22 | + return Single.value(_cachedColors!); |
| 23 | + } |
| 24 | + |
| 25 | + return useCancellationToken((cancelToken) async { |
| 26 | + final json = await _client.getJson(_url, cancelToken: cancelToken) |
| 27 | + as Map<String, dynamic>; |
| 28 | + |
| 29 | + return _cachedColors = _toColorMap(json); |
| 30 | + }); |
| 31 | + }); |
45 | 32 | } |
46 | 33 |
|
| 34 | + static BuiltMap<String, Color> _toColorMap(Map<String, dynamic> json) => |
| 35 | + (json.map((key, value) { |
| 36 | + final color = value['color']; |
| 37 | + return MapEntry( |
| 38 | + key, |
| 39 | + color is String ? colorFromHex(color) : null, |
| 40 | + ); |
| 41 | + }) |
| 42 | + ..removeWhere((key, value) => value == null)) |
| 43 | + .cast<String, Color>() |
| 44 | + .build(); |
| 45 | + |
47 | 46 | @visibleForTesting |
48 | 47 | static Color colorFromHex(String hex) { |
49 | 48 | hex = hex.replaceAll('#', ''); |
|
0 commit comments