Skip to content

Instantly share code, notes, and snippets.

@steprobe
Created March 19, 2021 12:07
Show Gist options
  • Save steprobe/274a96e5b381d52299eb2b41f98b664e to your computer and use it in GitHub Desktop.
Save steprobe/274a96e5b381d52299eb2b41f98b664e to your computer and use it in GitHub Desktop.
Observable Repo pattern using BroadcastChannel
@ExperimentalCoroutinesApi
@FlowPreview
class MentionsRepository(
private val middleEnd: MiddleEnd,
private val mentionsDao: MentionDao,
private val mapper: MentionsMapper
) {
private val mentionsBroadcastChannel = BroadcastChannel<DataState<List<MentionDisplayModel>>>(Channel.BUFFERED)
fun observeMentions() = mentionsBroadcastChannel.asFlow()
suspend fun loadMentions() {
try {
emitCachedMentions()
mentionsBroadcastChannel.send(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) {
mentionsBroadcastChannel.send(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()) {
mentionsBroadcastChannel.send(DataState.Success(mapper.mapToDisplayModelList(mentions)))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment