git.iko.soy/parseable-android
on 3b7ea33 help sign in
67 lines 2.3 kB history raw
1package com.parseable.android.ui.screens.alerts
3import androidx.lifecycle.ViewModel
4import androidx.lifecycle.viewModelScope
5import com.parseable.android.data.model.Alert
6import com.parseable.android.data.model.ApiResult
7import com.parseable.android.data.repository.ParseableRepository
8import dagger.hilt.android.lifecycle.HiltViewModel
9import kotlinx.coroutines.flow.MutableStateFlow
10import kotlinx.coroutines.flow.StateFlow
11import kotlinx.coroutines.flow.asStateFlow
12import kotlinx.coroutines.flow.update
13import kotlinx.coroutines.launch
14import javax.inject.Inject
16data class AlertsState(
17 val alerts: List<Alert> = emptyList(),
18 val isLoading: Boolean = false,
19 val error: String? = null,
20 val alertToDelete: Alert? = null,
23@HiltViewModel
24class AlertsViewModel @Inject constructor(
25 private val repository: ParseableRepository,
26) : ViewModel() {
28 private val _state = MutableStateFlow(AlertsState())
29 val state: StateFlow<AlertsState> = _state.asStateFlow()
31 fun refresh() {
32 viewModelScope.launch {
33 _state.update { it.copy(isLoading = true, error = null) }
34 when (val result = repository.listAlerts()) {
35 is ApiResult.Success -> {
36 val sorted = result.data.sortedBy { a ->
37 (a.name ?: a.title ?: "").lowercase()
38 }
39 _state.update { it.copy(alerts = sorted, isLoading = false) }
40 }
41 is ApiResult.Error -> {
42 _state.update { it.copy(isLoading = false, error = result.userMessage) }
43 }
44 }
45 }
46 }
48 fun requestDelete(alert: Alert) {
49 _state.update { it.copy(alertToDelete = alert) }
50 }
52 fun cancelDelete() {
53 _state.update { it.copy(alertToDelete = null) }
54 }
56 fun deleteAlert(alertId: String) {
57 viewModelScope.launch {
58 _state.update { it.copy(alertToDelete = null, isLoading = true, error = null) }
59 when (val result = repository.deleteAlert(alertId)) {
60 is ApiResult.Success -> refresh()
61 is ApiResult.Error -> {
62 _state.update { it.copy(isLoading = false, error = result.userMessage) }
63 }
64 }
65 }
66 }