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

33 lines
1017 B
Kotlin
Raw Normal View History

2019-08-19 16:50:33 +02:00
package com.github.apognu.otter.repositories
import android.content.Context
import kotlinx.coroutines.CoroutineScope
2019-08-19 16:50:33 +02:00
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Job
2020-07-13 23:32:42 +02:00
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
2019-08-19 16:50:33 +02:00
interface Upstream<D> {
2019-10-31 16:17:37 +01:00
fun fetch(size: Int = 0): Flow<Repository.Response<D>>
2019-08-19 16:50:33 +02:00
}
2020-07-13 23:32:42 +02:00
abstract class Repository<D : Any> {
protected val scope: CoroutineScope = CoroutineScope(Job() + IO)
2020-07-13 23:32:42 +02:00
data class Response<D>(val data: List<D>, val page: Int, val hasMore: Boolean)
2019-08-19 16:50:33 +02:00
abstract val context: Context?
abstract val upstream: Upstream<D>
2020-07-13 23:32:42 +02:00
fun fetch(size: Int = 0) = channelFlow {
2019-10-31 16:17:37 +01:00
upstream
.fetch(size)
2020-07-13 23:32:42 +02:00
.map { response -> Response(onDataFetched(response.data), response.page, response.hasMore) }
.collect { response -> send(Response(response.data, response.page, response.hasMore)) }
2019-08-19 16:50:33 +02:00
}
protected open fun onDataFetched(data: List<D>) = data
}