android_catalogue1-3 Exercise 3: Why a Transaction =================================================== Without a transaction, saveItem is several separate writes: insert the item, delete the old links, insert the new links. Each write is committed on its own. If the app is killed after the item insert but before the link inserts: - A new item exists but has none of the tags the user chose. - For an edit, the old links may already be deleted while the new ones were never written, so the item silently loses its tags. Nothing crashes, and nothing tells the user. The database is internally valid but the data is wrong. With db.withTransaction { ... } the writes are one unit: SQLite commits them all together or, if the process dies or an exception is thrown part way, rolls them all back. After a restart the item is either completely saved (with its tags) or exactly as it was before. No half-saved state is ever visible, which is the "atomic" in "saves atomically". (Foreign keys do not stop this problem: a missing link is not an invalid reference, it is just missing data.)