Florian
01/30/2021, 3:56 PMinline fun <ResultType, RequestType> networkBoundResource(
crossinline query: () -> Flow<ResultType>,
crossinline fetch: suspend () -> RequestType,
crossinline saveFetchResult: suspend (RequestType) -> Unit,
crossinline onFetchSuccess: () -> Unit = { },
crossinline onFetchFailed: (Throwable) -> Unit = { },
crossinline shouldFetch: (ResultType) -> Boolean = { true }
) = flow {
val data = query().first()
val flow = if (shouldFetch(data)) {
emit(Resource.Loading(data))
try {
saveFetchResult(fetch())
onFetchSuccess()
query().map { Resource.Success(it) }
} catch (t: Throwable) {
onFetchFailed(t)
query().map { Resource.Error(t, it) }
}
} else {
query().map { Resource.Success(it) }
}
emitAll(flow)
}
Nir
01/30/2021, 4:19 PMNir
01/30/2021, 4:20 PMNir
01/30/2021, 4:33 PMobject
but can also factor our and group together their logic with a class if they preferHaris Khan
01/30/2021, 4:34 PMHaris Khan
01/30/2021, 4:35 PMFlorian
01/30/2021, 7:08 PMFlorian
01/30/2021, 7:22 PMFlorian
01/30/2021, 7:31 PMinline
makes the code more efficient? And the code growth seems negligible to meHaris Khan
01/30/2021, 7:34 PMFlorian
01/30/2021, 7:38 PMHaris Khan
01/30/2021, 7:40 PMNir
01/30/2021, 8:51 PMNir
01/30/2021, 8:55 PMinterface NetworkResourceHandler<ResultType, ResourceType> {
fun query(): Flow<ResultType>
suspend fun fetch(): RequestType
suspend fun saveFetchResult(requestType: RequestType)
fun onFetchSuccess() { }
fun onFetchFailed(throwable: Throwable) {}
fun shouldFetch(resultType: ResultType): Boolean { true }
)
fun <ResultType, RequestType> networkBoundResource(handler: NetworkResourceHandler<ResultType, RequestType>) { ... }
Nir
01/30/2021, 8:56 PMobject
syntax looks just as good as calling with lambdas IMHO, but also having the ability to just write a class that inherits the interface is niceFlorian
01/30/2021, 9:59 PM