Files
forkmessager/client-mobile/profiles/presentation/viewmodel/ProfileViewModel.kt
Халимов Рустам 1fb1be47dd Приложение
2026-04-14 01:15:54 +03:00

75 lines
2.5 KiB
Kotlin

package profiles.presentation.viewmodel
import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import profiles.data.remote.dto.ProfileDto
import profiles.domain.repository.ProfileRepository
import javax.inject.Inject
data class ProfileState(
val profile: ProfileDto? = null,
val isLoading: Boolean = false,
val error: String? = null,
val isSaving: Boolean = false
)
@HiltViewModel
class ProfileViewModel @Inject constructor(
private val repository: ProfileRepository
) : ViewModel() {
private val _state = MutableStateFlow(ProfileState())
val state: StateFlow<ProfileState> = _state.asStateFlow()
fun loadProfile(id: String? = null) {
viewModelScope.launch {
_state.value = _state.value.copy(isLoading = true)
val result = if (id == null) {
repository.getMyProfile()
} else {
repository.getProfile(id)
}
result.onSuccess { profile ->
_state.value = _state.value.copy(profile = profile, isLoading = false)
}.onFailure { error ->
_state.value = _state.value.copy(error = error.message, isLoading = false)
}
}
}
fun updateProfile(displayName: String?, bio: String?, avatarUri: Uri? = null) {
viewModelScope.launch {
_state.value = _state.value.copy(isSaving = true)
// 1. Обновляем аватар, если он выбран
avatarUri?.let {
repository.uploadAvatar(it)
}
// 2. Обновляем текстовые данные
repository.updateProfile(displayName, bio)
.onSuccess { updatedProfile ->
_state.value = _state.value.copy(profile = updatedProfile, isSaving = false)
}
.onFailure { error ->
_state.value = _state.value.copy(error = error.message, isSaving = false)
}
}
}
fun removeAvatar() {
viewModelScope.launch {
repository.removeAvatar().onSuccess { updatedProfile ->
_state.value = _state.value.copy(profile = updatedProfile)
}
}
}
}