android5-7 Exercise 1: Retrofit into Room
======================================
// Module build.gradle.kts (versions are placeholders; the converter coordinates are to be confirmed)
dependencies {
implementation("com.squareup.retrofit2:retrofit:")
implementation("com.squareup.retrofit2:converter-kotlinx-serialization:")
}
import retrofit2.http.GET
interface NotesApi {
// suspend: Retrofit runs it off the main thread for you
@GET("posts")
suspend fun getNotes(): List
}
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
object NetworkModule {
val notesApi: NotesApi by lazy {
Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/") // https, so no cleartext issue
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
.create(NotesApi::class.java)
}
}
@Entity(
tableName = "notes",
indices = [Index(value = ["remoteId"], unique = true)]
)
data class NoteEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val text: String,
val createdAt: Long = System.currentTimeMillis(),
val remoteId: Long? = null // the server's id, or null for a note made here
)
// In AppDatabase: raise the version (schema changed)
@Database(entities = [NoteEntity::class], version = 2, exportSchema = false)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(notes: List)
// DTO to entity: the server's id goes in remoteId, our own id is generated
fun RemoteNoteDto.toEntity() = NoteEntity(text = title, remoteId = id)
sealed interface RefreshResult {
data object Success : RefreshResult
data object NoConnection : RefreshResult
data class ServerError(val code: Int) : RefreshResult
data object BadReply : RefreshResult
}
// In NotesRepository
suspend fun refresh(): RefreshResult
import java.io.IOException
import kotlinx.serialization.SerializationException
import retrofit2.HttpException
class DefaultNotesRepository(
private val noteDao: NoteDao,
private val api: NotesApi
) : NotesRepository {
// getNotesStream, addNote and deleteNote are unchanged: the UI still reads only from Room
override suspend fun refresh(): RefreshResult =
try {
val remote = api.getNotes()
noteDao.insertAll(remote.map { it.toEntity() }) // write into the single source of truth
RefreshResult.Success
} catch (e: IOException) {
RefreshResult.NoConnection
} catch (e: HttpException) {
RefreshResult.ServerError(e.code())
} catch (e: SerializationException) {
RefreshResult.BadReply
}
}
val notesRepository: NotesRepository by lazy {
DefaultNotesRepository(database.noteDao(), NetworkModule.notesApi)
}
data class NotesUiState(
val notes: List = emptyList(),
val isLoading: Boolean = false,
val isRefreshing: Boolean = false, // new
val userMessage: String? = null
)
private val isRefreshing = MutableStateFlow(false)
val uiState: StateFlow =
combine(repository.getNotesStream(), message, isRefreshing) { notes, userMessage, refreshing ->
NotesUiState(
notes = notes,
isLoading = false,
isRefreshing = refreshing,
userMessage = userMessage
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NotesUiState(isLoading = true)
)
fun refresh() {
viewModelScope.launch {
isRefreshing.value = true
val result = repository.refresh()
isRefreshing.value = false
when (result) {
RefreshResult.Success -> Unit
RefreshResult.NoConnection -> message.value = "No connection"
is RefreshResult.ServerError -> message.value = "Server error (${result.code})"
RefreshResult.BadReply -> message.value = "Unexpected reply from the server"
}
}
}
// In NotesScreen: a refresh button and a spinner
Row {
Button(onClick = onRefresh, enabled = !state.isRefreshing) { Text("Refresh") }
if (state.isRefreshing) CircularProgressIndicator()
}
Also: onRefresh = viewModel::refresh in NotesRoute and a parameter onRefresh: () -> Unit in NotesScreen.
Uninstall the app first (the schema changed to version 2 and there is no migration; development only).
Expected: after Refresh, the server's notes appear in the list; in aeroplane mode, restarting the app still shows them (they are in Room). Pressing Refresh offline shows "No connection".
Report the converter dependency you actually used (the chapter's coordinates are unconfirmed) and what you saw. Code unrun.