Skip to content

Commit

Permalink
Fix caching logic
Browse files Browse the repository at this point in the history
  • Loading branch information
CrisBarreiro committed Apr 10, 2024
1 parent cb4dc82 commit f426d21
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
28 changes: 15 additions & 13 deletions app/src/main/java/com/duckduckgo/app/history/HistoryRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import io.reactivex.Single

interface HistoryRepository {
fun getHistoryObservable(): Single<List<HistoryEntry>>

fun saveToHistory(
url: String,
title: String?,
Expand All @@ -38,11 +39,7 @@ class RealHistoryRepository(
private var cachedHistoryEntries: List<HistoryEntry>? = null

override fun getHistoryObservable(): Single<List<HistoryEntry>> {
return if (cachedHistoryEntries != null) {
Single.just(cachedHistoryEntries)
} else {
fetchAndCacheHistoryEntries()
}
return Single.just(cachedHistoryEntries ?: fetchAndCacheHistoryEntries())
}

override fun saveToHistory(
Expand All @@ -51,15 +48,20 @@ class RealHistoryRepository(
query: String?,
isSerp: Boolean,
) {
historyDao.updateOrInsertVisit(url, title ?: "", query, isSerp, currentTimeProvider.currentTimeMillis())
historyDao.updateOrInsertVisit(
url,
title ?: "",
query,
isSerp,
currentTimeProvider.currentTimeMillis(),
)
fetchAndCacheHistoryEntries()
}
private fun fetchAndCacheHistoryEntries(): Single<List<HistoryEntry>> {
return historyDao.getHistoryEntriesWithVisits()
.map { entries ->
entries.mapNotNull { it.toHistoryEntry() }.also {
cachedHistoryEntries = it
}
}

private fun fetchAndCacheHistoryEntries(): List<HistoryEntry> {
return historyDao
.getHistoryEntriesWithVisits()
.mapNotNull { it.toHistoryEntry() }
.also { cachedHistoryEntries = it }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,12 @@ import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import io.reactivex.Single

@Dao
interface HistoryDao {
@Transaction
@Query("SELECT * FROM history_entries")
fun getHistoryEntriesWithVisits(): Single<List<HistoryEntryWithVisits>>
fun getHistoryEntriesWithVisits(): List<HistoryEntryWithVisits>

@Transaction
fun updateOrInsertVisit(url: String, title: String, query: String?, isSerp: Boolean, date: Long) {
Expand Down

0 comments on commit f426d21

Please sign in to comment.