이 클래스는 GetxController와 같이 동일한 수명 주기( onInit(), onReady(), onClose())를 가지고 있다.
그러나 그 안에 "logic"이 없다.(?) GetX 종속성 주입 시스템에 이 하위 클래스를 메모리에서 제거할 수 없다.
따라서 Get.find()를 사용하여 controller에 항상 연결할 수 있고 활성 상태로 유지하는 데 매우 유용하다. 예: ApiService, StorageService, CacheService.
Future<void> main() async {
await initServices(); /// AWAIT SERVICES INITIALIZATION.
runApp(SomeApp());
}
/// Is a smart move to make your Services intiialize before you run the Flutter app.
/// as you can control the execution flow (maybe you need to load some Theme configuration,
/// apiKey, language defined by the User... so load SettingService before running ApiService.
/// so GetMaterialApp() doesnt have to rebuild, and takes the values directly.
void initServices() async {
print('starting services ...');
/// Here is where you put get_storage, hive, shared_pref initialization.
/// or moor connection, or whatever that's async.
await Get.putAsync(() => DbService().init());
await Get.putAsync(SettingsService()).init();
print('All services started...');
}
class DbService extends GetxService {
Future<DbService> init() async {
print('$runtimeType delays 2 sec');
await 2.delay();
print('$runtimeType ready!');
return this;
}
}
class SettingsService extends GetxService {
void init() async {
print('$runtimeType delays 1 sec');
await 1.delay();
print('$runtimeType ready!');
}
}
GetxService를 삭제하는 유일한 방법은 앱의 "Hot Reboot"와 같은 Get.reset()을 사용하는 것이다. 따라서 앱 수명 동안 클래스 인스턴스의 절대 지속성이 필요한 경우 GetxService를 사용하는게 좋다.
출처
728x90
'Flutter' 카테고리의 다른 글
[Flutter / 일반] instance of 'Class' 활용 (0) | 2022.03.15 |
---|---|
[Flutter / GetX] binding 사용하기 (0) | 2022.03.09 |
[Flutter / GetX] GetView를 상속받는 이유 (0) | 2022.03.08 |
[Flutter / 일반] enum을 활용한 분기 (0) | 2022.03.08 |
[Flutter / 일반] API의 json 활용하기; Factory, fromJson, toJson (0) | 2022.03.08 |