Untitled
unknown
plain_text
9 months ago
1.6 kB
8
Indexable
import 'dart:async';
import 'dart:math';
enum NetworkStatus { pending, approved, failed }
class MockApiService {
NetworkStatus _status = NetworkStatus.pending;
final StreamController<NetworkStatus> _statusController = StreamController.broadcast();
final Random _random = Random();
final Duration mockDuration;
MockApiService({this.mockDuration = const Duration(seconds: 5)}) {
_simulateStatusChange();
}
/// Exposes a real-time stream of network status changes.
Stream<NetworkStatus> get statusStream => _statusController.stream;
Future<NetworkStatus> fetchStatus() async {
await Future.delayed(const Duration(seconds: 1)); // Simulate network delay
return _status;
}
/// Simulates status transitions, with a chance of failure before approval.
void _simulateStatusChange() {
Timer.periodic(mockDuration, (timer) {
if (_status == NetworkStatus.pending) {
if (_random.nextDouble() < 0.3) {
_status = NetworkStatus.failed;
} else {
_status = NetworkStatus.approved;
}
_statusController.add(_status);
// Stop the timer once we hit an approved state
if (_status == NetworkStatus.approved) {
timer.cancel();
}
}
});
}
/// Retry logic: Allows retrying failed requests.
void retry() {
if (_status == NetworkStatus.failed) {
_status = NetworkStatus.pending;
_statusController.add(_status);
_simulateStatusChange();
}
}
/// Ensures the stream is properly closed when not needed.
void dispose() {
_statusController.close();
}
}
Editor is loading...
Leave a Comment