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

Access Redux Store via Isolate #69

Closed
ghost opened this issue Aug 3, 2018 · 2 comments
Closed

Access Redux Store via Isolate #69

ghost opened this issue Aug 3, 2018 · 2 comments

Comments

@ghost
Copy link

ghost commented Aug 3, 2018

Hi,

I'm creating a chat app and would want to sync contacts on a different thread, than the main thread - using an isolate probably.

How can I connect to flutter store via an isolate?

@brianegan
Copy link
Owner

brianegan commented Aug 3, 2018

Hey there -- I'd generally handle this in the Middleware layer. Overall, Isolates are very restricted on what data can be sent back and forth. Unfortunately, Streams are one of those things that cannot be passed back and forth, and the Store contains a Stream. Therefore, it isn't possible to pass the Store itself from one Isolate to another.

Therefore, I'd recommend creating a Middleware that synced the Contacts on a separate isolate, and returns those contacts to the middleware when it's finished syncing. Then, the middleware can dispatch the results.

For more info on running heavy json parsing operations in a separate isolate, you can check out this recipe: https://flutter.io/cookbook/networking/background-parsing/

It would look something like this:

class Contact {
  final String name;

  Contact(this.name);
}

class ContactsReceivedAction {
  final List<Contact> contacts;

  ContactsReceivedAction(this.contacts);
}

class ContactsErrorAction {
  final Object error;

  ContactsErrorAction(this.error);
}

void isolateMiddleware(
  Store<AppState> store,
  dynamic action,
  NextDispatcher next,
) async {
  if (action is ClearCompletedAction) {
    try {
      // Use the `compute` function to make the network call / parse json in
      // a separate isolate.
      final contacts = await compute(fetchContacts, '');

      store.dispatch(ContactsReceivedAction(contacts));
    } catch (e) {
      store.dispatch(ContactsErrorAction(e));
    }
  }

  next(action);
}

List<Contact> fetchContacts(String _) {
  return [Contact('Brian')];
}

@brianegan
Copy link
Owner

Hey @adityasodhani -- did this help out?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant