d-markey / squadron

Multithreading and worker thread pool for Dart / Flutter, to offload CPU-bound and heavy I/O tasks to Isolate or Web Worker threads.
https://pub.dev/packages/squadron
MIT License
79 stars 0 forks source link

does this package work with freezed? #24

Closed DarkHeros09 closed 11 months ago

DarkHeros09 commented 11 months ago

Hi

does this package work with freezed? if yes can you show an example from the code below?

its fromJson, and toJson that i want to use.

Thanks.

@freezed
class ProfileDTO with _$ProfileDTO {
  const factory ProfileDTO({
    required int id,
    required String name,
  }) = _ProfileDTO;
  const ProfiletDTO._();
  factory ProfileDTO.fromJson(Map<String, dynamic> json) =>
      _$ProfileDTOFromJson(json);

}
d-markey commented 11 months ago

Hello,

Squadron was designed to wrap services and run them in dedicated threads (Isolates/Web Workers). The idea is to have CPU-bound or heavy-I/O tasks execute without interfering too much with the main event loop that's used for UI.

ProfileDTO does not really match that definition as it simply constructs one instance with two simple fields. I don't see any heavy CPU or I/O operations.

Why would you need Squadron to extract two fields from a Map?

DarkHeros09 commented 11 months ago

Hello,

Squadron was designed to wrap services and run them in dedicated threads (Isolates/Web Workers). The idea is to have CPU-bound or heavy-I/O tasks execute without interfering too much with the main event loop that's used for UI.

ProfileDTO does not really match that definition as it simply constructs one instance with two simple fields. I don't see any heavy CPU or I/O operations.

Why would you need Squadron to extract two fields from a Map?

Hey d-markey

Thanks for your response, but it didn't quite answer my question. I was hoping for a simple answer regarding compatibility with the "freezed" package. Also, I used ProfileDTO as an example, so there's no need for additional fields.

Thanks

d-markey commented 11 months ago

Well, you can try this:

import 'my_service.activator.g.dart';
part 'my_service.worker.g.dart';

@SquadronService()
class MyService {
  @SquadronMethod()
  FutureOr<List<ProfileDTO>> loadList(String json) {
    final list = jsonDecode(json) as List;
    return list.map((item) => ProfileDTO.fromJson(item)).toList();
  }
}

You will need to dart run build_runner build your project, then you can invoke the service in a separate Isolate, eg:

void main(List<String> arguments) async {
  final worker = MyServiceWorker();
  await worker.start();
  try {
    final json = '[{"id":1,"name":"Profile A"},'
        '{"id":2,"name":"Profile B"},'
        '{"id":3,"name":"Profile C"}]';
    final profiles = await worker.loadList(json); // runs in a separate Isolate
    print('Got ${profiles.length} profiles');
    for (var p in profiles) {
      print(' * $p');
    }
  } finally {
    worker.stop();
  }
}