40 lines
1.2 KiB
Dart
40 lines
1.2 KiB
Dart
/// 약속: 정한 시간 뒤에 한 번 끈다 ([schedule]). 입력 = 기다릴 시간 (0 이하면 바로 끔), 출력 = 끌 시각 [stopAt] (기다리지 않으면 null).
|
|
/// [cancel] 하면 끄지 않는다. [stopNow] 는 기다리지 않고 바로 끈다. 다시 [schedule] 하면 앞의 것은 잊는다. 오류 = 끄는 함수의 오류 (바로 끌 때만 돌려줌).
|
|
/// 쓰는 곳: Tor (화면을 떠난 뒤 잠시 켜 둠 - 관리자 결정 10/11)
|
|
library;
|
|
|
|
import 'dart:async';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
class IdleStop {
|
|
IdleStop(this.onStop);
|
|
|
|
final Future<void> Function() onStop;
|
|
final stopAt = ValueNotifier<DateTime?>(null);
|
|
Timer? _timer;
|
|
|
|
Future<void> schedule(Duration after) async {
|
|
cancel();
|
|
if (after <= Duration.zero) return onStop();
|
|
stopAt.value = DateTime.now().add(after);
|
|
_timer = Timer(after, () {
|
|
_timer = null;
|
|
stopAt.value = null;
|
|
unawaited(onStop());
|
|
});
|
|
}
|
|
|
|
/// 기다리지 않고 지금 끈다 ([cancel] 뒤 끄는 함수)
|
|
Future<void> stopNow() {
|
|
cancel();
|
|
return onStop();
|
|
}
|
|
|
|
void cancel() {
|
|
_timer?.cancel();
|
|
_timer = null;
|
|
stopAt.value = null;
|
|
}
|
|
}
|