42 lines · 1.9 KB · KotlinRaw
package com.cottondb.androidimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.navigation.Routeimport com.cottondb.android.work.reader.ReaderDetailModelimport com.cottondb.android.work.reader.ReaderListModelimport com.cottondb.android.work.reader.ReaderRepositoryimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlow/** Route visits own their writes, first-open stamps, and observed web address across rotation. */class ReaderModels(core: CottonCalling, private val scope: CoroutineScope) { private val repository = ReaderRepository(core) private var list: ReaderListModel? = null private val pages = mutableMapOf<String, ReaderPageVisit>() fun list(): ReaderListModel = list ?: ReaderListModel(repository, scope).also { list = it } fun page(id: String): ReaderPageVisit = pages.getOrPut(id) { ReaderPageVisit(ReaderDetailModel(id, repository, scope)) } fun retain(routes: List<Route>) { if (Route.Reader !in routes) { list?.close(); list = null } val ids = routes.filterIsInstance<Route.ReaderPage>().map { it.id }.toSet() pages.keys.filterNot(ids::contains).forEach { pages.remove(it)?.model?.close() } }}data class ReaderWebState(val liveAddress: String? = null, val failure: String? = null, val attempt: Long = 0)class ReaderPageVisit(val model: ReaderDetailModel) { private val mutableWeb = MutableStateFlow(ReaderWebState()) val web = mutableWeb.asStateFlow() fun navigated(address: String, title: String?) { mutableWeb.value = mutableWeb.value.copy(liveAddress = address, failure = null) model.learnTitleIfNeeded(title) } fun failed(reason: String) { mutableWeb.value = mutableWeb.value.copy(failure = reason) } fun retryWeb() { mutableWeb.value = mutableWeb.value.copy(failure = null, attempt = mutableWeb.value.attempt + 1) }}