Created
March 19, 2021 14:23
-
-
Save steprobe/bf68915a2dfed54d1960fedcb2934aaa to your computer and use it in GitHub Desktop.
Observable Repo pattern using shared flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ExperimentalCoroutinesApi | |
@FlowPreview | |
class MentionsRepository( | |
private val middleEnd: MiddleEnd, | |
private val mentionsDao: MentionDao, | |
private val mapper: MentionsMapper | |
) { | |
private val _mentions = MutableSharedFlow<DataState<List<MentionDisplayModel>>>() | |
val mentions = _mentions.asSharedFlow() | |
suspend fun loadMentions() { | |
try { | |
emitCachedMentions() | |
_mentions.emit(DataState.Loading) | |
val request = GqlRequest(GET_MENTIONS, MentionsRequest(Slice(10))) | |
val response = middleEnd.getMentions(request) | |
val mentions = response.data.mentions.edges?.mapNotNull { it.node } | |
mentions?.let { mentionsDao.insertMentions(mentions) } | |
emitCachedMentions() | |
} catch (ex: Exception) { | |
_mentions.emit(DataState.Error(ex)) | |
} | |
} | |
suspend fun markMentionAsRead(mentionId: String) { | |
val recordsUpdated = mentionsDao.markMentionAsRead(mentionId) | |
instalog("Updated $recordsUpdated records") | |
emitCachedMentions() | |
} | |
private suspend fun emitCachedMentions() { | |
val mentions = mentionsDao.getMentions() | |
if (mentions.isNotEmpty()) { | |
_mentions.emit(DataState.Success(mapper.mapToDisplayModelList(mentions))) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment