stop method

Future<void> stop()

Stop receiving messages from native td json client, use this wisely

Implementation

Future<void> stop() async {
  if (!_running) {
    return;
  }
  if (_stopping != null) {
    return;
  }
  _stopping = Completer();
  // Need to wait isolate finishing last receive loop to prevent the error: [Client.cpp:277] Receive is called after Client destroy, or simultaneously from different threads
  // Flows:
  // - send custom event to td native
  //   - must use `testReturnError` as event, because others like `testSquareInt` can't be send after `authorizationStateClosed`
  // - isolate receive the event
  // - isolate send special type to main
  // - isolate break the loop
  // - main receive the type
  // - kill isolate
  _client.send({
    "@type": "testReturnError",
    "error": {
      // should prevent conflicts with td's code, but there is no code list in official doc, so here's using just a big number.
      "code": 9527
    }
  });
  await _stopping;
  _killIsolate();
  _stopping = null;
  _running = false;
}