Otter-App-Android-Funkwhale/app/src/main/java/com/github/apognu/otter/models/Mediator.kt

77 lines
2.5 KiB
Kotlin
Raw Normal View History

2020-08-03 15:22:52 +02:00
package com.github.apognu.otter.models
import android.content.Context
import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
2020-09-26 17:26:42 +02:00
import com.couchbase.lite.Database
import com.github.apognu.otter.models.api.FunkwhaleArtist
2020-08-03 15:22:52 +02:00
import com.github.apognu.otter.models.domain.Artist
import com.github.apognu.otter.repositories.ArtistsRepository
import com.github.apognu.otter.utils.AppContext
import com.github.apognu.otter.utils.Cache
import com.github.apognu.otter.utils.log
2020-09-26 17:26:42 +02:00
import com.molo17.couchbase.lite.doInBatch
import com.molo17.couchbase.lite.from
import com.molo17.couchbase.lite.select
import com.molo17.couchbase.lite.where
import kotlinx.coroutines.Dispatchers.IO
2020-08-03 15:22:52 +02:00
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.take
2020-09-26 17:26:42 +02:00
import kotlinx.coroutines.withContext
2020-08-03 15:22:52 +02:00
import org.koin.core.KoinComponent
@OptIn(ExperimentalPagingApi::class)
2020-09-26 17:26:42 +02:00
class Mediator(private val context: Context, private val database: Database, private val repository: ArtistsRepository) : RemoteMediator<Int, Artist>(), KoinComponent {
override suspend fun load(loadType: LoadType, state: PagingState<Int, Artist>): MediatorResult {
loadType.log()
2020-08-03 15:22:52 +02:00
return try {
val key = when (loadType) {
LoadType.REFRESH -> 1
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> {
Cache.get(context, "key")?.readLine()?.toInt() ?: return MediatorResult.Success(endOfPaginationReached = true)
}
}
2020-09-26 17:26:42 +02:00
val response = withContext(IO) {
repository.fetch((key - 1) * AppContext.PAGE_SIZE).take(1).first()
}
2020-08-03 15:22:52 +02:00
2020-09-26 17:26:42 +02:00
database.doInBatch {
2020-08-03 15:22:52 +02:00
if (loadType == LoadType.REFRESH) {
Cache.delete(context, "key")
2020-09-26 17:26:42 +02:00
select("_id")
.from(database)
.where { "type" equalTo "artist" }
.execute()
.forEach { delete(getDocument(it.getString(0))) }
2020-08-03 15:22:52 +02:00
}
Cache.set(context, "key", (key + 1).toString().toByteArray())
2020-09-26 17:26:42 +02:00
FunkwhaleArtist.persist(database, response.data, (key + 1) * 100)
listeners.forEach {
it()
listeners.remove(it)
2020-08-03 15:22:52 +02:00
}
}
return MediatorResult.Success(endOfPaginationReached = !response.hasMore)
} catch (e: Exception) {
MediatorResult.Error(e)
}
}
2020-09-26 17:26:42 +02:00
private var listeners: MutableList<() -> Unit> = mutableListOf()
fun addListener(listener: () -> Unit) {
listeners.add(listener)
}
2020-08-03 15:22:52 +02:00
}