Avoid illegal cast in RealStore.stream (#69)

* Avoid illegal cast in

* remove commented out code

* remove wildecards

* ktlint

* optimize imports

* don't print  in exception message to avoid PII leak
This commit is contained in:
Eyal Guthmann 2020-01-17 16:29:17 -08:00 committed by GitHub
parent bc6c47833d
commit 5f2fb35da9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 11 deletions

View file

@ -22,7 +22,7 @@ package com.dropbox.android.external.store4
* class to represent each response. This allows the flow to keep running even if an error happens
* so that if there is an observable single source of truth, application can keep observing it.
*/
sealed class StoreResponse<T> {
sealed class StoreResponse<out T> {
/**
* Represents the source of the Response.
*/
@ -81,11 +81,10 @@ sealed class StoreResponse<T> {
else -> null
}
@Suppress("UNCHECKED_CAST")
internal fun <R> swapType(): StoreResponse<R> = when (this) {
is Error -> Error(error, origin)
is Loading -> Loading(origin)
is Data -> Data(value = value as R, origin = origin)
is Data -> throw IllegalStateException("cannot swap type for StoreResponse.Data")
}
}

View file

@ -29,7 +29,6 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.transform
@ -81,10 +80,11 @@ internal class RealStore<Key : Any, Input : Any, Output : Any>(
override fun stream(request: StoreRequest<Key>): Flow<StoreResponse<Output>> {
return if (sourceOfTruth == null) {
@Suppress("UNCHECKED_CAST")
createNetworkFlow(
request = request,
networkLock = null
)
) as Flow<StoreResponse<Output>> // when no source of truth Input == Output
} else {
diskNetworkCombined(request, sourceOfTruth)
}.onEach {
@ -150,11 +150,11 @@ internal class RealStore<Key : Any, Input : Any, Output : Any>(
.transform {
// left is Fetcher while right is source of truth
if (it is Either.Left) {
if (it.value !is StoreResponse.Data<*>) {
if (it.value !is StoreResponse.Data) {
emit(it.value.swapType())
}
// network sent something
if (it.value is StoreResponse.Data<*>) {
if (it.value is StoreResponse.Data) {
// unlocking disk only if network sent data so that fresh data request never
// receives disk data by mistake
diskLock.complete(Unit)
@ -183,7 +183,7 @@ internal class RealStore<Key : Any, Input : Any, Output : Any>(
private fun createNetworkFlow(
request: StoreRequest<Key>,
networkLock: CompletableDeferred<Unit>?
): Flow<StoreResponse<Output>> {
): Flow<StoreResponse<Input>> {
return fetcherController
.getFetcher(request.key)
.onStart {
@ -196,8 +196,6 @@ internal class RealStore<Key : Any, Input : Any, Output : Any>(
origin = ResponseOrigin.Fetcher
)
)
}.map {
it.swapType<Output>()
}
}
}