|
1 | 1 | package com.surrus.common.repository |
2 | 2 |
|
| 3 | +import com.squareup.sqldelight.runtime.coroutines.asFlow |
| 4 | +import com.squareup.sqldelight.runtime.coroutines.mapToList |
3 | 5 | import com.surrus.common.remote.Assignment |
4 | 6 | import com.surrus.common.remote.PeopleInSpaceApi |
| 7 | +import com.surrus.peopleinspace.db.PeopleInSpaceDatabase |
5 | 8 | import kotlinx.coroutines.Dispatchers |
6 | 9 | import kotlinx.coroutines.GlobalScope |
| 10 | +import kotlinx.coroutines.flow.collect |
7 | 11 | import kotlinx.coroutines.launch |
8 | 12 |
|
| 13 | +expect fun createDb() : PeopleInSpaceDatabase |
| 14 | + |
9 | 15 | class PeopleInSpaceRepository { |
10 | 16 | private val peopleInSpaceApi = PeopleInSpaceApi() |
| 17 | + private val peopleInSpaceDatabase = createDb() |
| 18 | + private val peopleInSpaceQueries = peopleInSpaceDatabase.peopleInSpaceQueries |
| 19 | + |
| 20 | + init { |
| 21 | + GlobalScope.launch (Dispatchers.Main) { |
| 22 | + fetchAndStorePeople() |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + fun fetchPeopleAsFlow() = peopleInSpaceQueries.selectAll(mapper = { name, craft -> |
| 27 | + Assignment(name = name, craft = craft) |
| 28 | + }).asFlow().mapToList() |
11 | 29 |
|
12 | | - suspend fun fetchPeople() : List<Assignment> { |
| 30 | + suspend fun fetchAndStorePeople() { |
13 | 31 | val result = peopleInSpaceApi.fetchPeople() |
14 | | - return result.people |
| 32 | + result.people.forEach { |
| 33 | + peopleInSpaceQueries.insertItem(it.name, it.craft) |
| 34 | + } |
15 | 35 | } |
16 | 36 |
|
| 37 | + // called from iOS/watchOS client |
17 | 38 | fun fetchPeople(success: (List<Assignment>) -> Unit) { |
18 | 39 | GlobalScope.launch(Dispatchers.Main) { |
19 | | - success(fetchPeople()) |
| 40 | + fetchPeopleAsFlow().collect { |
| 41 | + success(it) |
| 42 | + } |
20 | 43 | } |
21 | 44 | } |
22 | 45 | } |
0 commit comments