Overview
The ClientsRepository provides CRUD operations for managing clients in the Greenhouse Admin system. All methods are suspend functions that return Result<T> for consistent error handling.
Methods
getClients()
Fetches all clients from the backend.
suspend fun getClients(): Result<List<Client>>
Returns
Result containing a list of Client objects or an error
getClientById()
Fetches a specific client by ID.
suspend fun getClientById(id: Long): Result<Client>
Parameters
Returns
Result containing the Client object or an error
createClient()
Creates a new client.
suspend fun createClient(client: Client): Result<Client>
Parameters
The client data to create
Returns
Result containing the created Client object or an error
updateClient()
Updates an existing client.
suspend fun updateClient(client: Client): Result<Client>
Parameters
The client data to update (must include a valid id)
Returns
Result containing the updated Client object or an error
deleteClient()
Deletes a client by ID.
suspend fun deleteClient(id: Long): Result<Unit>
Parameters
Returns
Result indicating success or error
Usage Example
class ClientsViewModel(
private val clientsRepository: ClientsRepository
) : ViewModel() {
private val _clients = MutableStateFlow<List<Client>>(emptyList())
val clients: StateFlow<List<Client>> = _clients.asStateFlow()
private val _error = MutableStateFlow<String?>(null)
val error: StateFlow<String?> = _error.asStateFlow()
init {
loadClients()
}
fun loadClients() {
viewModelScope.launch {
clientsRepository.getClients()
.onSuccess { _clients.value = it }
.onFailure { _error.value = it.message }
}
}
fun createClient(client: Client) {
viewModelScope.launch {
clientsRepository.createClient(client)
.onSuccess { loadClients() }
.onFailure { _error.value = it.message }
}
}
fun deleteClient(id: Long) {
viewModelScope.launch {
clientsRepository.deleteClient(id)
.onSuccess { loadClients() }
.onFailure { _error.value = it.message }
}
}
}
Dependency Injection
Inject the repository using Koin in your Composables:
import org.koin.compose.viewmodel.koinViewModel
@Composable
fun ClientsScreen() {
val viewModel: ClientsViewModel = koinViewModel()
val clients by viewModel.clients.collectAsState()
// UI implementation
}