4

I have this class and use "reactive" state management e.g.

"".obs

Now I plan to initialize my state from local storage (get_storage) onInit()

problem:

where do I persist my data? As soon as some state changes, I want to persist it as well.

I tried using a listener but it never fires.

Currently I have this:

class CosController extends GetxController {
  final box = GetStorage();

  RxString econtactnr = ''.obs;

  @override
  void onInit() {
    super.onInit();
    addListener(() { //NEVER fires
      print('hellowwww listener');
    });
    econtactnr.value = box.read('econtactnr') ?? '';
}

What is a best practice to store state to disk in GetXControllers using reactive state management?

EDIT: I noticed that you can do:

    econtactnr.listen((x) {
      box.write('econtactnr', econtactnr.value);
    });

question: is that ok? do I have to cancel that subscription as well?

1 Answer 1

9
+50

GetX provides Workers for this type of functionality. The ever method can listen and store the updated value whenever it changes.

Try this in your onInit

  @override
  void onInit() {
    super.onInit();
    econtactnr.value = box.read('econtactnr') ?? '';
    ever(
      econtactnr,
      (value) {
        box.write('econtactnr', value);
      },
    );
  }

This will work and persist as long as you have await GetStorage.init(); happening before you initialize with Get.put(CosController());

If you need that to be stored throughout the entire lifecycle of your app, then you don't need worry about disposing it because you always want it listening.

If you do want to dispose it for whatever reason, you could save the listener into a Worker variable.

 Worker worker;

  @override
  void onInit() {
    super.onInit();
    econtactnr.value = box.read('econtactnr') ?? '';
    worker = ever(
      econtactnr,
      (value) {
        box.write('econtactnr', value);
        debugPrint(value);
      },
    );
  }

Then dispose by using worker.dispose();

2
  • ah, easy to overlook as I'm sure most do not associate worker with listener. Or should one?
    – Toskan
    Apr 28, 2021 at 13:08
  • Yes I would say so. That's what the Workers do, listen and provide callbacks on value changes. As you discovered you can listen to a GetX stream without workers, but to me Workers provide a more pleasant syntax and offer some cool utility methods for when you need more fine grain control over what happens and when.
    – Loren.A
    Apr 28, 2021 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.