forked from android/compose-samples
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3 from arrow-kt/feature/article-details
Article details - Add algebra and different states
- Loading branch information
Showing
2 changed files
with
103 additions
and
12 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
JetNews/app/src/main/java/com/example/jetnews/ui/article/ArticleAlgebra.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package com.example.jetnews.ui.article | ||
|
||
import arrow.fx.IO | ||
import arrow.fx.extensions.fx | ||
import arrow.fx.typeclasses.seconds | ||
import com.example.jetnews.data._posts | ||
import com.example.jetnews.model.Post | ||
import com.example.jetnews.ui.ScreenState | ||
import kotlinx.coroutines.Dispatchers | ||
|
||
typealias ArticleState = ScreenState<Post> | ||
|
||
interface ArticleAlgebra { | ||
fun getArticle(postId: String, cb: (ArticleState) -> Unit): IO<Unit> | ||
|
||
companion object { | ||
operator fun invoke() = object : ArticleAlgebra { | ||
// for example purposes only :) | ||
var hasFailed = false | ||
|
||
override fun getArticle(postId: String, cb: (ArticleState) -> Unit): IO<Unit> = IO.fx { | ||
!effect { cb(ScreenState.Loading) } | ||
continueOn(Dispatchers.IO) | ||
val post = _posts.find { it.id == postId } | ||
!sleep(2.seconds) | ||
!effect(Dispatchers.Main) { | ||
cb( | ||
// Emulate brittle BE | ||
if (!hasFailed || post == null) { | ||
hasFailed = true | ||
ScreenState.Error(Unit) | ||
} else { | ||
ScreenState.Content(post) | ||
} | ||
) | ||
} | ||
} | ||
} | ||
} | ||
} |
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