Skip to content

Instantly share code, notes, and snippets.

@cohenItay
Last active July 19, 2022 05:42
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 cohenItay/521fb1201fecb186473ab1762964e806 to your computer and use it in GitHub Desktop.
Save cohenItay/521fb1201fecb186473ab1762964e806 to your computer and use it in GitHub Desktop.
MyRepositoryImplementation(...) : MyRepositoryInterface {
...
private val _myData = MutableStateFlow<ApiState<MyConcreteModel>>(ApiState.Idle())
override val myData: StateFlow<ApiState<MyConcreteModel>>
get() = _myData
override fun updateMyData() = someCoroutineScope.launch {
try {
_myData.value = ApiState.InWork(previousModel = null) // Instead of null you can contruct it with the previous model
val concreteDataModel = ..... // probably suspending function or some worker which will return the model
_myData.value = if (concreteDataModel.isValid())
ApiState.Success(model = concreteDataModel)
else
ApiState.Failure(
apiError = ApiError(...), // Construct your error
exception = null,
id = SOME_CONSTANT_ID // for internal repository use. will be explained later.
)
} catch (e: Exception) {
when (e) {
is SomeException1,
is SomeException2, ... -> {
_myData.value = ApiState.Failure(
apiError = null, // non-api error
exception = e
id = SOME_CONSTANT_ID // for internal repository use. will be explained later.
)
}
else ->
throw (e)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment