tekartik / sembast.dart

Simple io database
BSD 2-Clause "Simplified" License
763 stars 63 forks source link

Using sync to fetch data #361

Closed xOldeVx closed 6 months ago

xOldeVx commented 1 year ago

Sometimes i need to get all the records in the store, or just total of the records, i see all the methods to fetch it returns Future, is there a way to fetch it sync? i mean retrieve the data directly and not by Future?

In a good case i just need to add await in condition like this:

Future<bool> get isPlaylists async => (await playlistsStore.findFirst(db)) != null;
if (await db.isPlaylists) {
  ...
}

Instead of

bool get isPlaylists => playlistsStore.findFirst(db) != null;
if (db.isPlaylists) {
  ...
}

And in less pleasant cases i need use FutureBuilder

By the way, written in the document (https://github.com/tekartik/sembast.dart/blob/master/sembast/doc/open.md) Opening a database means loading its content in memory so if the data is already in the memory, why Future ?

alextekartik commented 1 year ago

That is a good question. All the API could possibly be synchronous however it could possibly hang the UI and maybe one day the database won't be loaded into memory on start, who knows. A subset of the API is available in a synchronous way since 3.4.8 (RecordRef.getSync, RecordRef.getSnapshotSync, RecordRef.existsSync) when basically it is just reading from a map. the query/find API might be more complex and I don't plan to make them synchronous at this time.

xOldeVx commented 1 year ago

Good news, i didn't know it's support sync way, ill try it soon

That is a good question. All the API could possibly be synchronous however it could possibly hang the UI and maybe one day the database won't be loaded into memory on start, who knows.

I didn't understand.. if the db is loaded into memory on start so all of the db is available, that a reason to possible use it in sync way

alextekartik commented 1 year ago

Yes, I have added synchronous read access in v3.4.9-1 just published (dev version). It is just that I don't recommend any synchronous access for a complex query (there is no real optimization) and sort order on big databases.