jean
11/11/2021, 7:45 PMsuspend fun <T> getListWrapperFromDbAnApi(
getFromDb: suspend () -> Either<InOrderError, ListWrapper<T>>,
shouldUpdate: (List<T>) -> Boolean,
getFromApi: suspend () -> Either<InOrderError, ListWrapper<T>>,
saveDataFromApi: suspend (List<T>) -> Either<InOrderError, Unit>
) = flow {
getFromDb().fold(
{ emit(Either.Left(it)) },
{ dbData ->
emit(Either.Right(dbData))
if (shouldUpdate(dbData.items)) {
getFromApi().fold(
{ emit(Either.Left(it)) },
{ apiData ->
if (dbData != apiData) {
emit(Either.Right(apiData))
saveDataFromApi(apiData.items)
}
}
)
}
}
)
}
I don’t think I can use either.eager
due to the nested suspend function error Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope
simon.vergauwen
11/12/2021, 8:33 AMeither { }
inside flow { }
since it’s suspend
, right?
So something like this.
flow {
either<InOrderError, Unit> {
val dbData = getFromDb().bind()
emit(dbData)
if(shouldUpdate(db.item)) {
val apiData = getFromApi().bind()
if(dbData != apiData ) {
emit(apiData.right())
saveDataFromApi(apiData.items)
}
}
}.fold({ emit(it.left()) }, ::identity)
}
jean
11/12/2021, 9:43 AMeither
, thanks @simon.vergauwen!jean
11/12/2021, 9:44 AM.fold({ emit(it.left()) }, ::identity)
is also pretty neatjean
11/12/2021, 7:43 PMflow {
val collector = this
either<InOrderError, Unit> {
val dbData = getFromDb().bind()
collector.emit(Either.Right(dbData))
if (shouldUpdate(dbData.items)) {
val apiData = getFromApi().bind()
if (dbData != apiData) {
collector.emit(Either.Right(apiData))
saveDataFromApi(apiData.items)
}
}
}.fold({ emit(it.left()) }, ::identity)
}
emit
isn’t directly accessible inside either
since lambdas have different scopesimon.vergauwen
11/12/2021, 7:54 PMsimon.vergauwen
11/12/2021, 7:54 PMeither
is even inline
simon.vergauwen
11/12/2021, 7:59 PMpakoito
11/13/2021, 1:14 PM.fold({ emit(it.left()) }, ::identity)
mapLeft
herejean
11/15/2021, 7:42 AMemit(dbData)
, using emit(dbData.right())
instead fixed the issue