62 lines
1.7 KiB
Kotlin
62 lines
1.7 KiB
Kotlin
package stories.presentation
|
|
|
|
import androidx.lifecycle.ViewModel
|
|
import androidx.lifecycle.viewModelScope
|
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
|
import kotlinx.coroutines.flow.*
|
|
import kotlinx.coroutines.launch
|
|
import stories.data.remote.api.StoryGroupDto
|
|
import stories.domain.repository.StoryRepository
|
|
import javax.inject.Inject
|
|
|
|
data class StoryState(
|
|
val storyGroups: List<StoryGroupDto> = emptyList(),
|
|
val isLoading: Boolean = false,
|
|
val error: String? = null
|
|
)
|
|
|
|
@HiltViewModel
|
|
class StoryViewModel @Inject constructor(
|
|
private val repository: StoryRepository
|
|
) : ViewModel() {
|
|
|
|
private val _state = MutableStateFlow(StoryState())
|
|
val state: StateFlow<StoryState> = _state.asStateFlow()
|
|
|
|
init {
|
|
loadStories()
|
|
}
|
|
|
|
fun loadStories() {
|
|
viewModelScope.launch {
|
|
_state.update { it.copy(isLoading = true) }
|
|
try {
|
|
val stories = repository.getStories()
|
|
_state.update { it.copy(storyGroups = stories, isLoading = false) }
|
|
} catch (e: Exception) {
|
|
_state.update { it.copy(isLoading = false, error = e.localizedMessage) }
|
|
}
|
|
}
|
|
}
|
|
|
|
fun markAsViewed(storyId: String) {
|
|
viewModelScope.launch {
|
|
try {
|
|
repository.viewStory(storyId)
|
|
} catch (e: Exception) {
|
|
// Ignore error for viewing
|
|
}
|
|
}
|
|
}
|
|
|
|
fun sendReaction(storyId: String, emoji: String) {
|
|
viewModelScope.launch {
|
|
try {
|
|
repository.addReaction(storyId, emoji)
|
|
} catch (e: Exception) {
|
|
// Handle error
|
|
}
|
|
}
|
|
}
|
|
}
|