git.iko.soy/parseable-android
on 0da331f help sign in
64 lines 2.1 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 _state.update { it.copy(alerts = result.data, isLoading = false) }
37 }
38 is ApiResult.Error -> {
39 _state.update { it.copy(isLoading = false, error = result.userMessage) }
40 }
41 }
42 }
43 }
45 fun requestDelete(alert: Alert) {
46 _state.update { it.copy(alertToDelete = alert) }
47 }
49 fun cancelDelete() {
50 _state.update { it.copy(alertToDelete = null) }
51 }
53 fun deleteAlert(alertId: String) {
54 viewModelScope.launch {
55 _state.update { it.copy(alertToDelete = null, isLoading = true, error = null) }
56 when (val result = repository.deleteAlert(alertId)) {
57 is ApiResult.Success -> refresh()
58 is ApiResult.Error -> {
59 _state.update { it.copy(isLoading = false, error = result.userMessage) }
60 }
61 }
62 }
63 }