Android-CleanArchitecture-Kotlin icon indicating copy to clipboard operation
Android-CleanArchitecture-Kotlin copied to clipboard

How to consume the result object of Either in Use Case Layer?

Open crjacinro opened this issue 6 years ago • 11 comments

So there is a repository layer and a user case layer. My use case calls the repository method (which returns either left or right and returns the User object as output when right.

image

crjacinro avatar Feb 12 '19 03:02 crjacinro

Hi. Any ideas?

crjacinro avatar Feb 12 '19 14:02 crjacinro

Not sure if this is correct but I can get it through result.either call and provide left or right callbacks, in which in the right callback, I can receive the User param.

crjacinro avatar Feb 12 '19 14:02 crjacinro

Have you tried .fold()?

Zhuinden avatar Feb 12 '19 14:02 Zhuinden

Have you tried .fold()?

Nope, that method is not available in either.

crjacinro avatar Feb 12 '19 14:02 crjacinro

You could use .flatMap(). it gives access to the Right object.

result.flatMap() { it -> repository.saveUser(it) }

ferdyrod avatar Feb 12 '19 15:02 ferdyrod

Hmm according to Arrow's Either implementation, there should be a fold method.

  inline fun <R> fold(ifLeft: (LEFT) -> R, ifRight: (RIGHT) -> R): R = when (this) {
    is Right -> ifRight(right)
    is Left -> ifLeft(left)
  }

Zhuinden avatar Feb 12 '19 15:02 Zhuinden

Hmm according to Arrow's Either implementation, there should be a fold method.

Yes, Arrow's implementation does have fold method. But this project has a custom Either, it doesn't have all of Arrow methods. It only has flatmap() and map().

ferdyrod avatar Feb 12 '19 15:02 ferdyrod

Well it's kinda neutered if it cannot fold. That's kinda the whole point of either 😄

Zhuinden avatar Feb 12 '19 15:02 Zhuinden

You could use .flatMap(). it gives access to the Right object.

result.flatMap() { it -> repository.saveUser(it) }

Thanks for this but doesn't flatmap transform data (instead of accessing object only) ? what is the impact of the flatmap operation to the original result variable?

crjacinro avatar Feb 12 '19 15:02 crjacinro

Also upon checking the code, what is the difference between map and flat map?

crjacinro avatar Feb 12 '19 16:02 crjacinro

flatMap expects some kind of Either<L, R> while map in case of Either most likely means mapRight which expects some kind of R.

Zhuinden avatar Feb 12 '19 16:02 Zhuinden