diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/api/email/MsgsCacheManager.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/api/email/MsgsCacheManager.kt index 04f0f5c9d4..ef3ea3da45 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/api/email/MsgsCacheManager.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/api/email/MsgsCacheManager.kt @@ -13,6 +13,9 @@ import com.flowcrypt.email.BuildConfig import com.flowcrypt.email.security.KeyStoreCryptoManager import com.flowcrypt.email.util.ProgressOutputStream import com.flowcrypt.email.util.cache.DiskLruCache +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext import okhttp3.internal.io.FileSystem import okio.buffer import java.io.File @@ -69,6 +72,20 @@ object MsgsCacheManager { return diskLruCache[key] } + /** + * Due to the realization of [DiskLruCache] we need to add a little delay + * before fetching [DiskLruCache.Snapshot] + */ + suspend fun getMsgSnapshotWithRetryStrategy(key: String): DiskLruCache.Snapshot? = + withContext(Dispatchers.IO) { + var attemptsCount = 0 + while (diskLruCache[key] == null && attemptsCount <= 50) { + delay(50) + attemptsCount++ + } + return@withContext diskLruCache[key] + } + fun isMsgExist(key: String): Boolean { val snapshot = diskLruCache[key] ?: return false return snapshot.getLength(0) > 0 diff --git a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/MsgDetailsViewModel.kt b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/MsgDetailsViewModel.kt index ec2858400f..6bb902d1d8 100644 --- a/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/MsgDetailsViewModel.kt +++ b/FlowCrypt/src/main/java/com/flowcrypt/email/jetpack/viewmodel/MsgDetailsViewModel.kt @@ -476,8 +476,10 @@ class MsgDetailsViewModel( Result.success(null) } if (result.status == Result.Status.SUCCESS) { - return@withContext MsgsCacheManager.getMsgSnapshot(messageEntity.id.toString()) - ?: throw java.lang.NullPointerException("Message not found in the local cache") + val snapshot = + MsgsCacheManager.getMsgSnapshotWithRetryStrategy(messageEntity.id.toString()) + return@withContext snapshot + ?: throw java.lang.NullPointerException("Message not found in the local cache (GOOGLE API)") } else throw result.exception ?: java.lang.IllegalStateException( context.getString( R @@ -553,8 +555,10 @@ class MsgDetailsViewModel( ) ) - return@execute MsgsCacheManager.getMsgSnapshot(messageEntity.id.toString()) - ?: throw java.lang.NullPointerException("Message not found in the local cache") + val snapshot = + MsgsCacheManager.getMsgSnapshotWithRetryStrategy(messageEntity.id.toString()) + return@execute snapshot + ?: throw java.lang.NullPointerException("Message not found in the local cache(IMAP)") } } }