Hello I am pretty new to Functional Programming of...
# announcements
k
Hello I am pretty new to Functional Programming of Kotlin. I am currently using Reactor for my project It is difficult to work in streams because once the instances of the stream changes it form, I can’t use the instances before change. ex) • Flux<AClass> -> Flux<BClass> -> SomeFunction that needs instances of AClass If above situation happens, I had to find AClass instances again, so the stream would go like • Flux<AClass> -> Flux<BClass> -> Flux<AClass> which I think is redundant and DB-work-expensive So I came up with this Idea to store the value of AClass, and then use it later without getting back.
Copy code
fun someFunction(something: Foo): Mono<Foo> {
        var zoo: Foo = Foo();

        fooRepository.find()
                .doOnNext { zoo = functionThatReturnsZoo() } // change the value of zoo
                .flatMap { ... }
                .flatMap { fooRepository.save(zoo) } // use zoo
    }
Will this be functional too?
b
I think you should do something like this
Copy code
return Mono.fromCallable(functionThatReturnsZoo() }
   .flatMap { ... }
   .doOnNext { fooRepository.save(it) }
but maybe you should describe a little bit more what you are trying to do. At the moment it's not very clear for me.
k
Thanks Boris, I have updated my question. Could you please kindly check? Thanks
b
What you need is the
map
method. You can then change one object to another. Like:
Copy code
fooRepository.find()
  .map { functionThatReturnsZoo(it) }
  .map { doSomethingElesWithIt(it) }
those methods can return any object you need, and it will be passed down the stream
ah, sorry ... i understood now what you need
if you need to keep the instance i would put it in a
Pair
or some custom class
Copy code
fooRepository.find()
  .map { Pair(it, functionThatReturnsZoo(it)) }
  .map { Pair(it.first, doSomethingElse(it.second) }
👍 3
k
But what if I want to go much further?
Copy code
fooRepository.find()
 .map { Pair(it, functionThatReturnsZoo(it)) }
 .map { Pair(it.first, doSomethingElse(it.second) 
 .map { Pair(it.first, doSomethingElse(it.second) }
 .map { Pair(it.first, doSomethingElse(it.second) }
}
Do I have to carry until the end?
b
It maybe somehow possible to branch out the steam and then merge or again. But I'm afraid I'm not very experienced with FP to tell how exactly