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?
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:
- Transactions manage multi-threading; e.g. a transaction is tied to a thread and vice versa.
- Read(-only) transactions never get blocked or block a write transaction.
- There can only be a single write transaction at any time; they run strictly one after the other (sequential).
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:
- Create a
Store()instance in your main isolate, as you normally would.
ByteData store.referencewhich contains the information about the native store.
- Send this reference to another isolate, via a
- In another isolate, receive the reference and open a local
Store.fromReference(getObjectBoxModel(), msg as ByteData).
- Now both isolates have their own Dart
Storeinstances 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.
Answered By – vaind
Answer Checked By – Willingham (FlutterFixes Volunteer)