refactor(android): the admin screens use the shared UiState and one load helper (DRY A4)

Users, Reports, Tag sources and the admin landing each declared their
own Loading/Empty/Success/Error sealed interface and the same
try / list / isEmpty / catch-into-ErrorCopy refresh. They use the shared
UiState<T> now (kept as typealiases for their state types), loading
through two new helpers in shared/UiState.kt: loadUiState, which turns a
failure into Error and lets cancellation through, and List.toListState,
which gives Empty for an empty list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 10:21:31 -05:00
co-authored by Claude Opus 5.5
parent 5853c52640
commit af5384e672
9 changed files with 110 additions and 133 deletions
@@ -33,11 +33,12 @@ import com.composables.icons.lucide.Users
import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository
import com.fabledsword.minstrel.admin.data.AdminTagSourcesRepository import com.fabledsword.minstrel.admin.data.AdminTagSourcesRepository
import com.fabledsword.minstrel.admin.data.AdminUsersRepository import com.fabledsword.minstrel.admin.data.AdminUsersRepository
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.Admin
import com.fabledsword.minstrel.nav.AdminQuarantine import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.nav.AdminTagSources
import com.fabledsword.minstrel.nav.AdminUsers import com.fabledsword.minstrel.nav.AdminUsers
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.LoadingCentered
@@ -57,11 +58,8 @@ import javax.inject.Inject
data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int) data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int)
sealed interface AdminLandingUiState { /** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */
data object Loading : AdminLandingUiState typealias AdminLandingUiState = UiState<AdminCounts>
data class Success(val counts: AdminCounts) : AdminLandingUiState
data class Error(val message: String) : AdminLandingUiState
}
// ─── ViewModel ─────────────────────────────────────────────────────── // ─── ViewModel ───────────────────────────────────────────────────────
@@ -72,7 +70,7 @@ class AdminLandingViewModel @Inject constructor(
private val tagSourcesRepo: AdminTagSourcesRepository, private val tagSourcesRepo: AdminTagSourcesRepository,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow<AdminLandingUiState>(AdminLandingUiState.Loading) private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow() val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
init { init {
@@ -80,21 +78,14 @@ class AdminLandingViewModel @Inject constructor(
} }
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job = viewModelScope.launch {
internal.value = AdminLandingUiState.Loading internal.value = UiState.Loading
try { internal.value = loadUiState {
val counts = coroutineScope { coroutineScope {
val qua = async { quarantineRepo.list().size } val qua = async { quarantineRepo.list().size }
val usr = async { usersRepo.list().size } val usr = async { usersRepo.list().size }
val tag = async { tagSourcesRepo.list().count { it.enabled } } val tag = async { tagSourcesRepo.list().count { it.enabled } }
AdminCounts(qua.await(), usr.await(), tag.await()) UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await()))
} }
internal.value = AdminLandingUiState.Success(counts)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminLandingUiState.Error(
ErrorCopy.fromThrowable(e),
)
} }
} }
} }
@@ -124,13 +115,13 @@ fun AdminLandingScreen(
modifier = Modifier.fillMaxSize().padding(inner), modifier = Modifier.fillMaxSize().padding(inner),
) { ) {
when (val s = state) { when (val s = state) {
AdminLandingUiState.Loading -> LoadingCentered() UiState.Loading, UiState.Empty -> LoadingCentered()
is AdminLandingUiState.Error -> EmptyState( is UiState.Error -> EmptyState(
title = "Couldn't load admin counts", title = "Couldn't load admin counts",
body = s.message, body = s.message,
) )
is AdminLandingUiState.Success -> SectionList( is UiState.Success -> SectionList(
counts = s.counts, counts = s.data,
navController = navController, navController = navController,
) )
} }
@@ -33,6 +33,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.fabledsword.minstrel.models.AdminQuarantineItemRef import com.fabledsword.minstrel.models.AdminQuarantineItemRef
import com.fabledsword.minstrel.nav.AdminQuarantine import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.EmptyState
@@ -72,19 +73,19 @@ fun AdminQuarantineScreen(
modifier = Modifier.fillMaxSize().padding(inner), modifier = Modifier.fillMaxSize().padding(inner),
) { ) {
when (val s = state) { when (val s = state) {
AdminQuarantineUiState.Loading -> LoadingCentered() UiState.Loading -> LoadingCentered()
AdminQuarantineUiState.Empty -> EmptyState( UiState.Empty -> EmptyState(
title = "No reports", title = "No reports",
body = "When listeners flag a track as a bad rip, wrong tags or " + body = "When listeners flag a track as a bad rip, wrong tags or " +
"a duplicate, their reports gather here.", "a duplicate, their reports gather here.",
) )
is AdminQuarantineUiState.Error -> ErrorRetry( is UiState.Error -> ErrorRetry(
title = "Couldn't load queue", title = "Couldn't load queue",
message = s.message, message = s.message,
onRetry = { viewModel.refresh() }, onRetry = { viewModel.refresh() },
) )
is AdminQuarantineUiState.Success -> QueueList( is UiState.Success -> QueueList(
rows = s.rows, rows = s.data,
onResolve = viewModel::resolve, onResolve = viewModel::resolve,
onRemoveFile = viewModel::removeFile, onRemoveFile = viewModel::removeFile,
onDeleteFile = viewModel::deleteFile, onDeleteFile = viewModel::deleteFile,
@@ -8,6 +8,9 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.events.EventsStream import com.fabledsword.minstrel.events.EventsStream
import com.fabledsword.minstrel.models.AdminQuarantineItemRef import com.fabledsword.minstrel.models.AdminQuarantineItemRef
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import com.fabledsword.minstrel.shared.toListState
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
@@ -20,12 +23,8 @@ import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
sealed interface AdminQuarantineUiState { /** The Reports queue, as the shared [UiState]. */
data object Loading : AdminQuarantineUiState typealias AdminQuarantineUiState = UiState<List<AdminQuarantineItemRef>>
data object Empty : AdminQuarantineUiState
data class Success(val rows: List<AdminQuarantineItemRef>) : AdminQuarantineUiState
data class Error(val message: String) : AdminQuarantineUiState
}
@HiltViewModel @HiltViewModel
class AdminQuarantineViewModel @Inject constructor( class AdminQuarantineViewModel @Inject constructor(
@@ -34,7 +33,7 @@ class AdminQuarantineViewModel @Inject constructor(
networkStatus: NetworkStatusController, networkStatus: NetworkStatusController,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow<AdminQuarantineUiState>(AdminQuarantineUiState.Loading) private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow() val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
/** /**
@@ -56,27 +55,14 @@ class AdminQuarantineViewModel @Inject constructor(
// when server health returns instead of waiting for a manual pull. // when server health returns instead of waiting for a manual pull.
viewModelScope.launch { viewModelScope.launch {
networkStatus.recoveries().collect { networkStatus.recoveries().collect {
if (internal.value is AdminQuarantineUiState.Error) refresh() if (internal.value is UiState.Error) refresh()
} }
} }
} }
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job = viewModelScope.launch {
internal.value = AdminQuarantineUiState.Loading internal.value = UiState.Loading
try { internal.value = loadUiState { repository.list().toListState() }
val rows = repository.list()
internal.value = if (rows.isEmpty()) {
AdminQuarantineUiState.Empty
} else {
AdminQuarantineUiState.Success(rows)
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminQuarantineUiState.Error(
ErrorCopy.fromThrowable(e),
)
}
} }
fun resolve(trackId: String) = act(trackId) { repository.resolve(it) } fun resolve(trackId: String) = act(trackId) { repository.resolve(it) }
@@ -85,13 +71,8 @@ class AdminQuarantineViewModel @Inject constructor(
private fun act(trackId: String, action: suspend (String) -> Unit) { private fun act(trackId: String, action: suspend (String) -> Unit) {
val before = internal.value val before = internal.value
if (before is AdminQuarantineUiState.Success) { if (before is UiState.Success) {
val filtered = before.rows.filterNot { it.trackId == trackId } internal.value = before.data.filterNot { it.trackId == trackId }.toListState()
internal.value = if (filtered.isEmpty()) {
AdminQuarantineUiState.Empty
} else {
AdminQuarantineUiState.Success(filtered)
}
} }
viewModelScope.launch { viewModelScope.launch {
try { try {
@@ -35,6 +35,7 @@ import androidx.navigation.NavHostController
import com.fabledsword.minstrel.models.AdminTagSourceRef import com.fabledsword.minstrel.models.AdminTagSourceRef
import com.fabledsword.minstrel.models.TagSourceTestResult import com.fabledsword.minstrel.models.TagSourceTestResult
import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.nav.AdminTagSources
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
@@ -66,19 +67,19 @@ fun AdminTagSourcesScreen(
modifier = Modifier.fillMaxSize().padding(inner), modifier = Modifier.fillMaxSize().padding(inner),
) { ) {
when (val s = state) { when (val s = state) {
AdminTagSourcesUiState.Loading -> LoadingCentered() UiState.Loading -> LoadingCentered()
AdminTagSourcesUiState.Empty -> EmptyState( UiState.Empty -> EmptyState(
title = "No tag sources", title = "No tag sources",
body = "Tag-enrichment providers register on the server; none are available.", body = "Tag-enrichment providers register on the server; none are available.",
) )
is AdminTagSourcesUiState.Error -> ErrorRetry( is UiState.Error -> ErrorRetry(
title = "Couldn't load tag sources", title = "Couldn't load tag sources",
message = s.message, message = s.message,
onRetry = { viewModel.refresh() }, onRetry = { viewModel.refresh() },
) )
is AdminTagSourcesUiState.Success -> TagSourceList( is UiState.Success -> TagSourceList(
providers = s.providers, providers = s.data.providers,
testResults = s.testResults, testResults = s.data.testResults,
onToggle = viewModel::setEnabled, onToggle = viewModel::setEnabled,
onSaveKey = viewModel::saveApiKey, onSaveKey = viewModel::saveApiKey,
onTest = viewModel::test, onTest = viewModel::test,
@@ -8,6 +8,8 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.models.AdminTagSourceRef import com.fabledsword.minstrel.models.AdminTagSourceRef
import com.fabledsword.minstrel.models.TagSourceTestResult import com.fabledsword.minstrel.models.TagSourceTestResult
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -16,15 +18,14 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
sealed interface AdminTagSourcesUiState { /** The tag sources and the last Test answer for each, by provider id. */
data object Loading : AdminTagSourcesUiState data class AdminTagSources(
data object Empty : AdminTagSourcesUiState val providers: List<AdminTagSourceRef>,
data class Success( val testResults: Map<String, TagSourceTestResult> = emptyMap(),
val providers: List<AdminTagSourceRef>, )
val testResults: Map<String, TagSourceTestResult>,
) : AdminTagSourcesUiState /** The Tag sources screen, as the shared [UiState]. */
data class Error(val message: String) : AdminTagSourcesUiState typealias AdminTagSourcesUiState = UiState<AdminTagSources>
}
@HiltViewModel @HiltViewModel
class AdminTagSourcesViewModel @Inject constructor( class AdminTagSourcesViewModel @Inject constructor(
@@ -32,7 +33,7 @@ class AdminTagSourcesViewModel @Inject constructor(
networkStatus: NetworkStatusController, networkStatus: NetworkStatusController,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow<AdminTagSourcesUiState>(AdminTagSourcesUiState.Loading) private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow() val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
init { init {
@@ -41,34 +42,28 @@ class AdminTagSourcesViewModel @Inject constructor(
// health returns instead of waiting for a manual pull. // health returns instead of waiting for a manual pull.
viewModelScope.launch { viewModelScope.launch {
networkStatus.recoveries().collect { networkStatus.recoveries().collect {
if (internal.value is AdminTagSourcesUiState.Error) refresh() if (internal.value is UiState.Error) refresh()
} }
} }
} }
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job = viewModelScope.launch {
internal.value = AdminTagSourcesUiState.Loading internal.value = UiState.Loading
try { internal.value = loadUiState {
val providers = repository.list() val providers = repository.list()
internal.value = if (providers.isEmpty()) { if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
AdminTagSourcesUiState.Empty
} else {
AdminTagSourcesUiState.Success(providers, emptyMap())
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminTagSourcesUiState.Error(ErrorCopy.fromThrowable(e))
} }
} }
fun setEnabled(id: String, enabled: Boolean) { fun setEnabled(id: String, enabled: Boolean) {
val before = internal.value as? AdminTagSourcesUiState.Success ?: return val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
// Optimistic toggle; reconcile via refresh() if the server rejects. // Optimistic toggle; reconcile via refresh() if the server rejects.
internal.value = before.copy( internal.value = UiState.Success(
providers = before.providers.map { before.copy(
if (it.id == id) it.copy(enabled = enabled) else it providers = before.providers.map {
}, if (it.id == id) it.copy(enabled = enabled) else it
},
),
) )
viewModelScope.launch { viewModelScope.launch {
try { try {
@@ -102,15 +97,17 @@ class AdminTagSourcesViewModel @Inject constructor(
) { ) {
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e)) TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e))
} }
val current = internal.value as? AdminTagSourcesUiState.Success ?: return@launch val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return@launch
internal.value = current.copy(testResults = current.testResults + (id to result)) internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result)))
} }
} }
private fun replaceProvider(updated: AdminTagSourceRef) { private fun replaceProvider(updated: AdminTagSourceRef) {
val current = internal.value as? AdminTagSourcesUiState.Success ?: return val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
internal.value = current.copy( internal.value = UiState.Success(
providers = current.providers.map { if (it.id == updated.id) updated else it }, current.copy(
providers = current.providers.map { if (it.id == updated.id) updated else it },
),
) )
} }
} }
@@ -49,6 +49,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.fabledsword.minstrel.models.AdminUserRef import com.fabledsword.minstrel.models.AdminUserRef
import com.fabledsword.minstrel.nav.AdminUsers import com.fabledsword.minstrel.nav.AdminUsers
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
@@ -197,10 +198,10 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
onAskDelete: (AdminUserRef) -> Unit, onAskDelete: (AdminUserRef) -> Unit,
) { ) {
when (state) { when (state) {
AdminUsersUiState.Loading -> item { CenteredHint("Loading users…") } UiState.Loading -> item { CenteredHint("Loading users…") }
AdminUsersUiState.Empty -> item { CenteredHint("No registered users.") } UiState.Empty -> item { CenteredHint("No registered users.") }
is AdminUsersUiState.Error -> item { CenteredHint(state.message) } is UiState.Error -> item { CenteredHint(state.message) }
is AdminUsersUiState.Success -> items(items = state.users, key = { it.id }) { user -> is UiState.Success -> items(items = state.data, key = { it.id }) { user ->
UserRow( UserRow(
user = user, user = user,
onSetAdmin = { onSetAdmin(user.id, it) }, onSetAdmin = { onSetAdmin(user.id, it) },
@@ -3,10 +3,12 @@ package com.fabledsword.minstrel.admin.ui
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.fabledsword.minstrel.admin.data.AdminUsersRepository import com.fabledsword.minstrel.admin.data.AdminUsersRepository
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.models.AdminUserRef import com.fabledsword.minstrel.models.AdminUserRef
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import com.fabledsword.minstrel.shared.toListState
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -15,12 +17,8 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
sealed interface AdminUsersUiState { /** The Users screen's list, as the shared [UiState]. */
data object Loading : AdminUsersUiState typealias AdminUsersUiState = UiState<List<AdminUserRef>>
data object Empty : AdminUsersUiState
data class Success(val users: List<AdminUserRef>) : AdminUsersUiState
data class Error(val message: String) : AdminUsersUiState
}
@HiltViewModel @HiltViewModel
class AdminUsersViewModel @Inject constructor( class AdminUsersViewModel @Inject constructor(
@@ -28,7 +26,7 @@ class AdminUsersViewModel @Inject constructor(
networkStatus: NetworkStatusController, networkStatus: NetworkStatusController,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow<AdminUsersUiState>(AdminUsersUiState.Loading) private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow() val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
init { init {
@@ -37,25 +35,14 @@ class AdminUsersViewModel @Inject constructor(
// when server health returns instead of waiting for a manual pull. // when server health returns instead of waiting for a manual pull.
viewModelScope.launch { viewModelScope.launch {
networkStatus.recoveries().collect { networkStatus.recoveries().collect {
if (internal.value is AdminUsersUiState.Error) refresh() if (internal.value is UiState.Error) refresh()
} }
} }
} }
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job = viewModelScope.launch {
internal.value = AdminUsersUiState.Loading internal.value = UiState.Loading
try { internal.value = loadUiState { repository.list().toListState() }
val users = repository.list()
internal.value = if (users.isEmpty()) {
AdminUsersUiState.Empty
} else {
AdminUsersUiState.Success(users)
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminUsersUiState.Error(ErrorCopy.fromThrowable(e))
}
} }
fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) { fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) {
@@ -70,13 +57,8 @@ class AdminUsersViewModel @Inject constructor(
fun delete(id: String) { fun delete(id: String) {
val before = internal.value val before = internal.value
if (before is AdminUsersUiState.Success) { if (before is UiState.Success) {
val filtered = before.users.filterNot { it.id == id } internal.value = before.data.filterNot { it.id == id }.toListState()
internal.value = if (filtered.isEmpty()) {
AdminUsersUiState.Empty
} else {
AdminUsersUiState.Success(filtered)
}
} }
viewModelScope.launch { viewModelScope.launch {
try { try {
@@ -95,9 +77,9 @@ class AdminUsersViewModel @Inject constructor(
action: suspend (String) -> Unit, action: suspend (String) -> Unit,
) { ) {
val before = internal.value val before = internal.value
if (before is AdminUsersUiState.Success) { if (before is UiState.Success) {
internal.value = AdminUsersUiState.Success( internal.value = UiState.Success(
before.users.map { if (it.id == id) mutate(it) else it }, before.data.map { if (it.id == id) mutate(it) else it },
) )
} }
viewModelScope.launch { viewModelScope.launch {
@@ -1,5 +1,8 @@
package com.fabledsword.minstrel.shared package com.fabledsword.minstrel.shared
import com.fabledsword.minstrel.api.ErrorCopy
import kotlinx.coroutines.CancellationException
/** /**
* Shared cache-first UI state for a screen / tab that resolves to a * Shared cache-first UI state for a screen / tab that resolves to a
* single payload. Mirrors the shape every screen had reinvented: * single payload. Mirrors the shape every screen had reinvented:
@@ -20,3 +23,22 @@ sealed interface UiState<out T> {
data class Success<T>(val data: T) : UiState<T> data class Success<T>(val data: T) : UiState<T>
data class Error(val message: String) : UiState<Nothing> data class Error(val message: String) : UiState<Nothing>
} }
/** This list as a state: [UiState.Empty] when it has nothing in it, else [UiState.Success]. */
fun <T> List<T>.toListState(): UiState<List<T>> = if (isEmpty()) UiState.Empty else UiState.Success(this)
/**
* Runs [load] and gives its answer as a state, for a screen that loads
* straight from the server (the admin screens). A failure becomes
* [UiState.Error] in ErrorCopy's words; cancellation passes through.
*/
suspend fun <T> loadUiState(load: suspend () -> UiState<T>): UiState<T> =
try {
load()
} catch (e: CancellationException) {
throw e
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
UiState.Error(ErrorCopy.fromThrowable(e))
}
@@ -6,6 +6,7 @@ import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.events.EventsStream import com.fabledsword.minstrel.events.EventsStream
import com.fabledsword.minstrel.events.LiveEvent import com.fabledsword.minstrel.events.LiveEvent
import com.fabledsword.minstrel.models.AdminQuarantineItemRef import com.fabledsword.minstrel.models.AdminQuarantineItemRef
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.testutil.MainDispatcherExtension import com.fabledsword.minstrel.testutil.MainDispatcherExtension
import io.mockk.coEvery import io.mockk.coEvery
import io.mockk.coVerify import io.mockk.coVerify
@@ -47,7 +48,7 @@ class AdminQuarantineViewModelTest {
coVerify(exactly = 1) { repository.removeFile("t1") } coVerify(exactly = 1) { repository.removeFile("t1") }
coVerify(exactly = 0) { repository.deleteFile(any()) } coVerify(exactly = 0) { repository.deleteFile(any()) }
assertEquals(AdminQuarantineUiState.Empty, viewModel.uiState.value) assertEquals(UiState.Empty, viewModel.uiState.value)
} }
@Test @Test
@@ -56,6 +57,6 @@ class AdminQuarantineViewModelTest {
coVerify(exactly = 1) { repository.deleteFile("t1") } coVerify(exactly = 1) { repository.deleteFile("t1") }
coVerify(exactly = 0) { repository.removeFile(any()) } coVerify(exactly = 0) { repository.removeFile(any()) }
assertEquals(AdminQuarantineUiState.Empty, viewModel.uiState.value) assertEquals(UiState.Empty, viewModel.uiState.value)
} }
} }