Kashismails
07/01/2024, 1:31 PMsealed interface SocketResponse<out T> {
data class Data<T>(val item: T) : SocketResponse<T>
data class Error(val exception: Throwable) : SocketResponse<Nothing>
object ConnectionLost : SocketResponse<Nothing>
object Loading : SocketResponse<Nothing>
}
I have this class and a function that returns a flow such as
fun SocketFun() = flow<SocketResponse>{
emit(SocketResonse.Data(SomeClass(variableA, variableB)
emit(SocketResonse.ConnectionLost)
}
Now flow can emit two different states of one parent, I want to make an extension to track state of flow such as this one
fun <T> Flow<T>.asResult(shouldEmit: Boolean = true): Flow<Result<T>> {
return this
.map<T, Result<T>> {
Result.Success(it)
}
.onStart { emit(Result.Loading) }
.catch {
if (it is Exception) {
errorLogger("resultException", it.message ?: "Exception in result Flow.")
if (shouldEmit) {
emit(Result.Error(it.getRealException()))
}
} else {
emit(Result.Error(CustomMessage.ExceptionMessage("System not responding.")))
}
}
}
However, i want to skip map because i dont want to map anything its either data or connection lost start and catch will be in the extension function. It wont work without map but i have to do this at multiple places in my codebase and dont want to repeat onstart buffer and catch everywhere as logic for all these will be same. What is the best way to handle this?