LoginSignup
0
1

More than 1 year has passed since last update.

Todoアプリで Multiplatform を目指す SQLDelight を使う

Last updated at Posted at 2022-08-10

前回の続きですが。

Reflector Recording.gif
👉 Jetpack Compose で Todo アプリを作ってみた - Qiita

SQLDelight を使います。

👉 Getting Started with Multiplatform - SQLDelight

テキストファイルに、テーブル、クエリーをSQLで記述して、

-- app/src/main/sqldelight/com/your/package/data/Todo.sq

CREATE TABLE todo (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  text TEXT NOT NULL,
  updated INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

selectAll:
SELECT * FROM todo ORDER BY updated DESC;

count:
SELECT COUNT(id) FROM todo;

insert:
INSERT INTO todo (text) VALUES (:text);

update:
UPDATE todo SET text = :text, updated = (strftime('%s', 'now')) WHERE id = :entryId;

delete:
DELETE FROM todo
WHERE id = :entryId;

ビルドすると、関連テーブルやクラスが自動作成され、そのまま使えるようになります。

class TodoRepository @Inject constructor(
  private val database: Database
) {

  fun load(): Flow<List<Todo>> {
    return database.todoQueries.selectAll().asFlow().mapToList(Dispatchers.IO)
  }

  fun count(): Flow<Long> {
    return database.todoQueries.count().asFlow().mapToOne(Dispatchers.IO)
  }

  fun insert(text: String) {
    database.todoQueries.insert(text)
  }

  fun update(id: Long, text: String) {
    database.todoQueries.update(text, id)
  }

  fun delete(id: Long) {
    database.todoQueries.delete(id)
  }

}

Flow に向けて作られており、Kotlin を使ったマルチプラットフォーム向けです。

👉 KMM や マルチプラットフォーム を見据えて SQLDelight で Repository

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1