Skip to content

Instantly share code, notes, and snippets.

@JYCabello
Last active December 2, 2019 07:32
Show Gist options
  • Save JYCabello/ef342cb5334b264a321a86580901fde2 to your computer and use it in GitHub Desktop.
Save JYCabello/ef342cb5334b264a321a86580901fde2 to your computer and use it in GitHub Desktop.
Using IO for the fruit repository insertOrUpdate
import arrow.core.None
import arrow.core.Option
import arrow.core.some
import arrow.fx.IO
fun insertOrUpdate(fruit: FruitMetadata): IO<Int> =
findByAuthorityId(fruit.fruitAuthorityId)
.flatMapNone { findByCouncilId(fruit.fruitCouncilId) }
.flatMapNone { findByName(fruit.name) }
.flatMap { it.fold({ insert(fruit) }, { id -> update(id, fruit) }) }
fun findByAuthorityId(authorityId: Int): IO<Option<Int>> = IO.just(None)
fun findByCouncilId(councilId: Int): IO<Option<Int>> = IO.just(None)
fun findByName(name: String): IO<Option<Int>> = IO.just(None)
fun insert(fruit: FruitMetadata): IO<Int> = IO.just(1)
fun update(id: Int, fruit: FruitMetadata): IO<Int> = IO.just(id)
fun <T> IO<Option<T>>.flatMapNone(block: () -> IO<Option<T>>): IO<Option<T>> =
this.flatMap { it.fold({ block() }, { t -> IO.just(t.some()) }) }
data class FruitMetadata(val color: String, val fruitAuthorityId: Int, val fruitCouncilId: Int, val name: String, val shape: String)
insertOrUpdate(FruitMetadata("yellow", 0, 0, "banana", "elongated")).attempt().unsafeRunSync().fold({
println("Failed with $it")
}, {
println("Id: $it") // Id: 1
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment