flutterdartobjectboxflutter-objectbox

ObjectBox Dart/Flutter multi-isolate access


Creating a separate thread for a question stated in a comment...

How does ObjectBox handle concurrent(by different threads/isolates) write requests? example of my use case: FCM "onBackgroundmessage" call runs in a different isolate, the same time multiple write requests might happen. "Hive" is failing in this case completely. Is there any inbuild solution in ObjectBox?


Solution

  • ObjectBox for dart is based on a native ObjectBox core library that handles concurrency using Transactions. Let me pick out few points relevant to the question:

    As for the isolates in Dart/Flutter - yes, they can safely access the same store, you just need to make sure it really is the same native store instance. To do so, you do the following steps:

    1. Create a Store() instance in your main isolate, as you normally would.
    2. Get ByteData store.reference which contains the information about the native store.
    3. Send this reference to another isolate, via a SendPort.
    4. In another isolate, receive the reference and open a local Store instance, using Store.fromReference(getObjectBoxModel(), msg as ByteData).
    5. Now both isolates have their own Dart Store instances which internally use the same underlying native store. Therefore, their transactions are synchronized, they both see the same data and get notifications on data changes. 🎉

    You can see the code I've just described this test case: https://github.com/objectbox/objectbox-dart/blob/461a948439dcc42f3956b7d21b232eb9c2bc26e1/objectbox/test/isolates_test.dart#L50

    Make sure you don't close the store while another isolate is still using it. Better not close it at all - that's best practice in normal applications without huge amounts of background work.