So in Rxjava terms, a Monad is the lambda inside t...

# functionalk

kenkyee

07/10/2018, 1:11 PMSo in Rxjava terms, a Monad is the lambda inside the .map operator?

r

rawtoast

07/10/2018, 1:28 PMNo RxJava experience, but:
The basic way to think about this is: A Monad is an object that holds a another object and provides two methods:

`map`

and `flatmap`

.
There are additional rules (Monad Laws, etc), but I wouldn’t look into that until you are comfortable with using existing monads.
You could see Java’s `Optional`

as a monad. It doesn’t strictly meet the criteria as it violates the Monad Laws, but as a beginner it may help to think of it as one.a

Andreas Sinz

07/10/2018, 1:37 PM😮 1

t

tmg

07/10/2018, 3:11 PM`flatMap`

is what Monad gives you (besides some garantees if you respect the monad laws). `map`

comes from Funtors. (I guess you could call Monads a "subclass" of Functors)tmg

07/10/2018, 3:13 PMYou can think of functors and monads as context or containers. But it's best if you know the math behind it

p

pakoito

07/10/2018, 3:45 PMMonad is an object you can create that describes the way RxJava’s Observables can be chained

pakoito

07/10/2018, 3:46 PM Copy code

```
interface ObservableMonad {
fun <A> just(a: A): Observable<A> = Observable.just(a)
fun <A, B> flatMap(obs: Observable<A>, f: (A) -> Observable<B>): Observable <B> = obs.flatMap(f)
}
```

pakoito

07/10/2018, 3:47 PMand you can pass that as a parameter through your program, describing how to chain Observables

pakoito

07/10/2018, 3:47 PMyou can create them for lists and such

pakoito

07/10/2018, 3:48 PM Copy code

```
interface ListMonad {
fun <A> just(a: A): List<A> = listOf(a)
fun <A, B> flatMap(list: List<A>, f: (A) -> List<B>): List <B> = list.flatMap(f)
}
```

pakoito

07/10/2018, 3:48 PMso you can abstract over them, and have special syntax

pakoito

07/10/2018, 3:49 PMor create whole programs that are polymorphic to these types and can be run using lists or observables, or option, and always behave the same because you only have those two operations…and any other operation derived from it

pakoito

07/10/2018, 3:50 PM Copy code

```
fun <A,B> map(list: List<A>, f: (A) -> B): List<B> =
list.flatMap { a -> just(f(a)) }
```

pakoito

07/10/2018, 3:52 PMso while

`Observable`

can be chained in a monadic way, you need extra language support to use the Monad abstraction effectivelypakoito

07/10/2018, 3:52 PMfor example, with async/await notation, what the article does as let!

pakoito

07/10/2018, 3:52 PMand arrow does like this: https://arrow-kt.io/docs/integrations/rx2/#observable-comprehensions

4 Views