ivk1800 / tdlib-dart

MIT License
19 stars 12 forks source link

The Necessity of an Isolate for Event Listener #13

Open cliftonlabrum opened 8 months ago

cliftonlabrum commented 8 months ago

I really appreciated the simplicity and clarity of your event listener example in the Readme:

import 'package:tdlib/td_client.dart';
import 'package:tdlib/td_api.dart' as td;

Future<void> main() async {
  final Client client = Client.create();

  client.updates.listen((td.TdObject event) async {
    print('update: ${event.toJson()}');
  });
  await client.initialize();
}

Is it a good idea to put that event listener on a background isolate? I've managed to do that like this:

startTelegram() async{
  final receivePort = ReceivePort();

  await Isolate.spawn(Telegram.to.listenUp, receivePort.sendPort, errorsAreFatal: true);

  receivePort.listen((data) async {
    print(data); //<-- JSON string
  });
}

class Telegram {
  Client? client;
  StreamSubscription<td.TdObject>? eventsSubscription;

  listenUp(SendPort sendPort) async {
    if (client != null) return;

    final Client newClient = Client.create();
    client = newClient;
    eventsSubscription?.cancel();

    newClient.initialize();
    eventsSubscription = client?.updates.listen((td.TdObject event) async {
      print('--- Event Received ---');
      sendPort.send(event.toJson()); //<-- Convert to JSON string
    });
  }
}

But the problem is an isolate ReceivePort can't send a complex object like a TdObject. So I have to serialize the data to JSON with .toJSON(). But when it reaches the listenevent back up in startTelegram (on the main thread), it's a string that I cannot turn back into a TdObject.

As far as I can tell, there is no .fromJson() option available in this library. Am I mistaken?

Am I prematurely optimizing by putting this listener in an isolate? Is it not necessary? Any other tips or suggestions?

Thank you! 😊

SantiiRepair commented 6 months ago

@cliftonlabrum Have you thought about creating a pull request?