Skip to content

Instantly share code, notes, and snippets.

@indrih17
Last active January 11, 2021 13:09
Show Gist options
  • Save indrih17/f9f7263abcbbbb7f17b06eef179f8665 to your computer and use it in GitHub Desktop.
Save indrih17/f9f7263abcbbbb7f17b06eef179f8665 to your computer and use it in GitHub Desktop.
class Lens<Entity : Any, Value : Any?>(
val get: (Entity) -> Value,
val set: (Entity, Value) -> Entity
)
fun <Entity : Any, Value : Any?> Flow<Entity>.lens(lens: Lens<Entity, Value>): Flow<Value> =
map { lens.get(it) }.distinctUntilChanged()
fun <Entity1 : Any, Entity2 : Any, Value : Any?> Lens<Entity1, Entity2>.compose(other: Lens<Entity2, Value>): Lens<Entity1, Value> =
Lens(
get = { entity -> other.get(get(entity)) },
set = { entity1: Entity1, value ->
val entity2: Entity2 = get(entity1)
set(entity1, other.set(entity2, value))
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment