Skip to content

Instantly share code, notes, and snippets.

@4gus71n
Created February 13, 2023 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4gus71n/ff2eb51ed19ae9861d78516c854d2d1c to your computer and use it in GitHub Desktop.
Save 4gus71n/ff2eb51ed19ae9861d78516c854d2d1c to your computer and use it in GitHub Desktop.
Example Use Case
package com.example.core.usecases
import com.example.core.model.Employee
import com.example.core.repositories.EmployeeRepository
import com.example.core.utils.ResultData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.*
class GetAllEmployeesUseCase(
private val employeeRepository: EmployeeRepository,
private val dispatcher: CoroutineDispatcher
) {
sealed class Callback {
data class OnSuccessfullyFetchedAllEmployees(
val list: List<Employee>
) : Callback()
object NoEmployeesListed : Callback()
object NoInternetConnectionError : Callback()
object UnknownError : Callback()
}
operator fun invoke(): Flow<Callback> {
return employeeRepository.getEmployees().map { result ->
if (result.isError) {
when (result.error) {
ResultData.Error.NO_CONNECTIVITY -> {
Callback.NoInternetConnectionError
}
else -> {
Callback.UnknownError
}
}
} else {
val employees = result.data
if (employees != null && employees.isNotEmpty()) {
Callback.OnSuccessfullyFetchedAllEmployees(employees)
} else {
Callback.NoEmployeesListed
}
}
}.flowOn(dispatcher)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment