I am developing a flutter application (at the time just for Android, but with iOS support planned for later). The application operates in two ways:
- Flutter UI with most of the business logic (Foreground isolate, started with the main method) (FG)
- Some automatic tasks performed on the background using android WorkManager (Which uses Flutter Background Isolate) (BG)
- Both isolates are using Database
Since we need to use Database in the “thread-safe” manner we are trying to use the Moor database framework, with the moor_ffi interface to talk to SQLite server.
Moor claims to achieve it’s “thread-safety” by spawning the third Isolate (MoorIsolate). This isolate is the only one that talks to the database. Queries executed in BG and FG are sent to this isolate using SendPort/ReceivePort, executed, and returned to caller Isolate.
However, all Moor examples suggest spawning MoorIsolate from FG isolate. Which draws my attention to the following concerns.
What happens to the MoorIsolate if the FG Isolate “dies”
1.1 If the user exits by pressing the back button on the last screen in Navigator?
1.2 If the APP is not visible for some time and the OS decides to free up its memory.
1.3 If users “force-kills” app in settings (this should ideally be the only case where MoorIsolate dies)
In BG isolate we are using IsolateNameServer to construct MoorIsolate. Is there any way we can detect if Isolate is still running?
After communication with moor developer and my own empiric test I have concluded following:
- If isolate dies, all isolates spawned from it dies along. This means that if MoorIsolate is spawned from FG isolate and FG isolate is stopped by any method MoorIsolate will die along.
- moor_ffi ships thread safe version of sqlite for android. This means it is OK to spawn MoorIsolate in FG and separate MoorIsolate (or no MoorIsolate at all) for BG.
- IsolateNameServer is only way to pass ports between FG and BG isolates. However there still may be race conditions.
Answered By – Martin Hlavňa
Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)