Skip to content

Commit

Permalink
Change return type of PostSourceFetcher#fetch to Result<String>
Browse files Browse the repository at this point in the history
Refactored reader presenter to fit these changes better
  • Loading branch information
msasikanth committed Feb 7, 2024
1 parent faa0681 commit 335df0e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,22 @@ class PostSourceFetcher(
private val dispatchersProvider: DispatchersProvider
) {

suspend fun fetch(link: String): String? {
suspend fun fetch(link: String): Result<String> {
return withContext(dispatchersProvider.io) {
try {
val response = httpClient.get(transformUrlToHttps(link))
if (
response.status == HttpStatusCode.OK &&
response.contentType()?.withoutParameters() == ContentType.Text.Html
) {
return@withContext response.bodyAsText()
val content = response.bodyAsText()
return@withContext Result.success(content)
}
} catch (e: Exception) {
// no-op
}

// TODO: Return [Result.failure] object to render different reader view
return@withContext null
return@withContext Result.failure(IllegalArgumentException("Failed to fetch the post"))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,25 +164,35 @@ class ReaderPresenter(

private fun articleShortcutClicked() {
coroutineScope.launch {
when (_state.value.postMode) {
RssContent -> {
_state.update { it.copy(postMode = InProgress) }
val content = postSourceFetcher.fetch(postLink).orEmpty()
val htmlContent = extractArticleHtmlContent(postLink, content)
_state.update { it.copy(content = htmlContent, postMode = Source) }
}
Source -> {
_state.update { it.copy(postMode = InProgress) }
val postContent = rssRepository.post(postLink).rawContent.orEmpty()
val htmlContent = extractArticleHtmlContent(postLink, postContent)
_state.update { it.copy(content = htmlContent, postMode = RssContent) }
}
val currentPostMode = _state.value.postMode
when (currentPostMode) {
RssContent -> loadSourceArticle()
Source -> loadRssContent()
InProgress,
Idle -> {
// no-op
}
}
}
}

private suspend fun loadRssContent() {
_state.update { it.copy(postMode = InProgress) }
val postContent = rssRepository.post(postLink).rawContent.orEmpty()
val htmlContent = extractArticleHtmlContent(postLink, postContent)
_state.update { it.copy(content = htmlContent, postMode = RssContent) }
}

private suspend fun loadSourceArticle() {
_state.update { it.copy(postMode = InProgress) }
val content = postSourceFetcher.fetch(postLink)

if (content.isSuccess) {
val htmlContent = extractArticleHtmlContent(postLink, content.getOrThrow())
_state.update { it.copy(content = htmlContent) }
}

_state.update { it.copy(postMode = Source) }
}
}
}

0 comments on commit 335df0e

Please sign in to comment.