flutter_foreground_task icon indicating copy to clipboard operation
flutter_foreground_task copied to clipboard

Cannot call the updated data of a singleton class from onEvent()

Open AmanMasipeddi opened this issue 3 years ago • 2 comments

I am having an issue with onEvent(). I have given interval and want to execute a specific code in that interval. However the code I want to execute contains variables which will be modified somewhere else in the app. But after the modification, the onEvent() is not giving the updated value.

ClassA {
ClassA._();

  factory ClassA() {
    _singleton ??= ClassA._();
    return _singleton!;
  }

  static ClassA? _singleton;
  int number = 0;

  void incrementNumber(){
   number = number + 1;
  }
}

// In onEvent()
@override
  Future<void> onEvent(DateTime timestamp, SendPort? sendPort) async {
    print(ClassA().number);
  }

Whenever I update the number from another place and then onEvent takes place, the number is always '0'. But it will be updated an updated value when ever I use it in another part of the app.

Thanks in Advance!

AmanMasipeddi avatar Jun 16 '22 06:06 AmanMasipeddi

You don't have any access to your main isolate inside your foreground task (which runs in a different isolate). You can try using send port or access value using build-in write and read methods.

behradkhadem avatar Jun 16 '22 14:06 behradkhadem

Thanks for you reply. I am registering the sendPort to a receive port like below.

bool _registerReceivePort(ReceivePort? receivePort) {
    _closeReceivePort();

    if (receivePort != null) {
      _receivePort = receivePort;
      _receivePort?.listen((message) {
        print(message);
      });

      return true;
    }
    return false;
  }

AmanMasipeddi avatar Jun 16 '22 14:06 AmanMasipeddi