如何正确地抽象类型转换函数



我有很多类似的方法:

override suspend fun getBalance(): Result<BigDecimal> = withContext(Dispatchers.IO) {
Log.d(TAG, "Fetching balance from data store")
val balance = balancePreferencesFlow.firstOrNull()
?: return@withContext Result.Error(CacheIsInvalidException)
return@withContext when (balance) {
is Result.Success -> {
if ((balance.data.timestamp + ttl) <= getCurrentTime()) {
deleteBalance()
Result.Error(CacheIsInvalidException)
} else {
resultOf { balance.data.toDomainType() }
}
}
is Result.Error -> balance
}
}

在那里,我正在从DataStore中收集某种类型的Flow,如果它是Success Result(具有类型T的数据参数(,我应该获取它的时间戳(它是一个数据类字段(,如果条件为true,则删除无效数据,如果为false,则返回转换后的Result。

转换函数看起来像这样:

fun BigDecimal.toPersistenceType(): Balance = Balance(
balanceAmount = this,
timestamp = getCurrentTime()
)
fun Balance.toDomainType(): BigDecimal = this.balanceAmount

我试着用这种方式制作一个抽象方法,但我不完全理解如何将lambda传递给它

suspend inline fun <reified T : Any, reified V : Any> getPreferencesDataStoreCache(
preferencesFlow: Flow<Result<V>>,
ttl: Long,
deleteCachedData: () -> Unit,
getTimestamp: () -> Long,
convertData: () -> T
): Result<T> {
val preferencesResult = preferencesFlow.firstOrNull()
return when (preferencesResult) {
is Result.Success -> {
if ((getTimestamp() + ttl) <= getCurrentTime()) {
deleteCachedData()
Result.Error(CacheIsInvalidException)
} else {
resultOf { preferencesResult.data.convertData() }
}
}
is Result.Error -> preferencesResult
else -> Result.Error(CacheIsInvalidException)
}
}

转换的lambda应该看起来像一个扩展方法。

结果类别:

sealed class Result<out T : Any> {
data class Success<out Type : Any>(val data: Type) : Result<Type>()
data class Error(val exception: Exception) : Result<Nothing>()
}

首先,我在这里看到了一些缓存工作,从我的角度来看,这些工作应该放在一个接口中。

interface Cache {
val timestamp: Long
fun clear()
}

如果缓存仍然为空,则可以将timestamp属性设置为null以返回null,这取决于您自己。

然后,我假设您需要的通用方法放在Result类中,因为它似乎只是自己的工作。

sealed class Result<out T : Any> {
data class Success<out Type : Any>(val data: Type) : Result<Type>()
data class Error(val exception: Exception) : Result<Nothing>()
fun <R : Any> convertIfValid(cache: Cache, ttl: Long, converter: (T) -> R) : Result<R> =
when (this) {
is Success -> {
if (cache.timestamp + ttl <= getCurrentTime()) {
cache.clear()
Error(CacheIsInvalidException())
} else {
Success(converter(data))
}
}
is Error -> this
}
}

也许把getCurrentTime方法也放在一些注入的实体中会更好,但这在本文中并不重要。顺便说一句,正如您在when中看到的,我没有放置else状态,因为它对于密封类来说是不必要的。

从你的代码中,我可以做一个缓存实现的例子,只是为了平衡:

class BalanceCache : Cache {
var balanceValue = Balance()
override val timestamp: Long
get() = balanceValue.timestamp
override fun clear() {
deleteBalance()
}
}

如果你需要我的更多例子,请给我更多关于你的代码的细节,你想在哪里使用它。

最新更新