Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decoding JSON in an Isolate #104

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

techouse
Copy link

@techouse techouse commented Oct 8, 2022

Since the JSON payloads can be quite large, using json.decode() on the main thread could cause janking in Flutter.

One solution would be to expose a method that does the decoding which defaults to json.decode but allow it to be overridden in order to use compute() or any other Isolate method.

I have swapped out all internal package references to

json.decode(response.body)

with

await algolia.decodeJson(response.body)

Here's an example of an override using compute():

import 'dart:async';
import 'dart:convert';
import 'package:algolia/algolia.dart';

class IsolateDecodingAlgolia extends Algolia {
  IsolateDecodingAlgolia.init({
    super.applicationId,
    super.apiKey,
    super.extraHeaders,
    super.extraUserAgents,
  });

  /// Override the default JSON decoder with an Isolated one using compute
  @override
  Future<dynamic> decodeJson(
    String source, {
    Object? Function(Object? key, Object? value)? reviver,
  }) => 
      compute(json.decode, source);
}

In pure Dart < 2.19 you have to either get creative with the low-level Isolate API or simply import the compute package.

Thankfully, Dart 2.19 will soon come with Isolate.run()

@override
Future<dynamic> decodeJson(
  String source, {
  Object? Function(Object? key, Object? value)? reviver,
}) => 
    Isolate.run(() => json.decode(source));

Another option would also be using a worker pool. The squadron package provides an excellent API and builder just for that purpose.

This addresses #103

@techouse techouse changed the title Decoding JSON in isolate Decoding JSON in an Isolate Oct 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant