https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
arrow
  • k

    kyleg

    02/03/2020, 2:10 AM
    Is
    LiveData
    a monad that would benefit from the Rx treatment in Arrow? Its got
    pure
    in
    MutableLiveData(…)
    ,
    Transformations.map(myLiveData, myTransformation)
    is
    map
    , and
    Transformations.switchMap(myLiveData, myTransformationFn)
    is like
    flatMap
    . And because it is lazy until there is a registered observer, it could be thought of as
    IO
    . I guess.
    IO.unsafeRunAsync
    is basically
    SomeLiveData.observe(…)
    That’s why I’m asking the experts here 🙂
    p
    s
    • 3
    • 10
  • k

    Kristian

    02/03/2020, 10:08 AM
    I would like to say a big thank you to @raulraja & @simon.vergauwen for the excellent training they delivered to our developers on functional programming and arrow. The quality of the material and technical expertise on the topics was top notch. 👍
    🎉 12
    💯 13
    ❤️ 13
    :arrow: 23
    s
    r
    • 3
    • 2
  • m

    mattmoore

    02/03/2020, 7:53 PM
    Question: If I have a function with return type
    EitherT<ForIO, E, A>
    and I want to run it via
    parMapN
    , how would I best accomplish this?
    j
    s
    • 3
    • 11
  • s

    Satyam Agarwal

    02/04/2020, 8:41 AM
    So.
    IO.effect(IO.dispatchers().io() + MDCContext())
    doesn’t work, but
    IO.effect(MDCContext())
    works. I am trying to put MDC correlation id on all the logs that gets produced on
    IO.dispatchers().io()
    s
    • 2
    • 25
  • m

    Mark Fisher

    02/04/2020, 12:31 PM
    Hi Arrow people, I've got another question on docs examples. I can't get the "Using DI to inject any object" examples compiling, and I'm getting stuck on them. The docs are here https://arrow-kt.io/docs/patterns/dependency_injection/ my code snippet to attempt similar is in thread...
    a
    • 2
    • 5
  • m

    mattmoore

    02/04/2020, 5:45 PM
    Hello everyone! I started experimenting with Arrow Fx
    0.11.0-SNAPSHOT
    last night using Ktor. I switched from
    EitherT
    over to
    IO<E, A>
    and got everything compiling and running. The weird thing is that with
    IO<E, A>
    if I respond with
    A
    in Ktor (where
    A
    is the successful data class I'm expecting),
    A
    gets serialized with
    { "b": { ... } }
    . At first I thought I had something still wrapped, but I inspected all the functions and types and still am getting that result. When I downgraded back to
    0.10.4
    and switched back to
    EitherT
    the response serializes properly without
    b
    and instead serializes to
    { ... }
    . Curious if anyone else has encountered this. Here's an example:
    fun getLeads(): IO<Exception, List<Lead>> =
            IO.fx<Exception, List<Lead>> {
                transaction {
                    Leads.selectAll().map { toLead(it) }
                }
            }
    
    val response = getLeads().attempt().map {
                    when (it) {
                        is Either.Left -> mapOf("error" to it.a.message)
                        is Either.Right -> present(it.b)
                    }
                }
                call.respond(response.suspended())
    It's entirely possible I'm misusing
    attempt
    here, not sure. The Ktor serialized response I get is:
    {
      "b": [
        {
          "id": 2,
          "firstName": "Matt",
          "lastName": "Moore"
        }
      ]
    }
    With
    EitherT
    :
    fun getLeads(): EitherT<ForIO, Exception, List<Lead>> = EitherT(
            IO {
                Right(
                        transaction {
                            Leads.selectAll().map { toLead(it) }
                        }
                )
            }.handleError { Left(Exception(it.message)) }
    )
    
    val response = getLeads().value().fix().map {
        when (it) {
            is Either.Left -> mapOf("error" to it.a.message)
            is Either.Right -> present(it.b)
        }
    }.suspended()
    call.respond(response)
    When I run this example with
    EitherT
    I get this response from Ktor:
    [
      {
        "id": 2,
        "firstName": "Matt",
        "lastName": "Moore"
      }
    ]
    Note that it no longer wraps in
    b
    Apologies for the long message!
    s
    • 2
    • 3
  • m

    Mark Fisher

    02/05/2020, 8:31 AM
    Hi again, I'm going to repeat a question that may have got lost in my previous one. I'm looking at the docs at https://arrow-kt.io/docs/patterns/dependency_injection/#using-di-to-inject-any-object but can't get the following to work (towards the end):
    with (Option.monadError()) {
      createId("123") shouldBe Some(123)
      // ...
    In the code above it,
    createId
    is an extension of
    MonadThrow
    not
    MonadError
    so this doesn't compile. How do I get a
    monadThrow
    from an
    Option
    to make this work?
    s
    p
    • 3
    • 10
  • k

    Kristian

    02/05/2020, 10:42 AM
    Thanks for the explanation! So it's also equivalent to:
    fun prepareAndSendMultiple(listMessages: List<Message>, connectionStringKey: String, queueKey: String): IO<Unit> =
             listMessages.parTraverse { message ->
                prepareAndSend(message, connectionStringKey, queueKey) // returns IO<Unit>
            }.unit()
    ?
    :arrow: 1
    s
    • 2
    • 4
  • g

    Gopal S Akshintala

    02/05/2020, 11:29 AM
    Hi, I get this compilation error, this code is from arrow-examples folder, has something changed?
    a
    s
    • 3
    • 9
  • g

    Gopal S Akshintala

    02/05/2020, 2:06 PM
    Can
    IO
    be used in conjunction with a reactive server (Like coroutines + Spring Reactor)?
    s
    • 2
    • 11
  • a

    Ahmed Ibrahim

    02/06/2020, 11:35 AM
    Hello, I'm trying to get my mind around Arrow (0.11.0-SNAPSHOT), and trying to implement a simple app using its FP power. I have this class that retrieves Ids from a service, and then use theses Ids to get the details in parallel, then combine the result into a list to be used in the ui layer. The problem now once an error happens, it just crashes even though I'm handling things with Either
    fold
    . What I'm doing wrong in my case? and how can I prevent this code from crashing?
    class GetStoriesListUseCase @Inject constructor(
        private val hackerNewsService: HackerNewsService
    ) {
    
        suspend fun topStories(
            pageNumber: Int,
            pageSize: Int = 100
        ): Either<Throwable, List<StoryUIModel>> =
            readTopStoriesIds(pageSize)
                .flatMap { getTopStoriesDetails(it) }
                .suspended()
    
        private fun getTopStoriesDetails(topStoriesIds: List<Id<Long>>): IO<Throwable, List<StoryUIModel>> =
            topStoriesIds.map { it.value() }.parTraverse { anId ->
                IO.effect(<http://Dispatchers.IO|Dispatchers.IO>) {
                    Timber.d("${Thread.currentThread().name}")
                    hackerNewsService.topStoryDetail(anId).toStoryUIModel()
                }
            }
    
        private fun readTopStoriesIds(pageSize: Int): IO<Throwable, List<Id<Long>>> =
            IO.effect {
                hackerNewsService.topStoriesIds().map { Id.just(it) }.take(pageSize)
            }
    
        private fun StoryDetails.toStoryUIModel() =
            StoryUIModel(id = id, title = title, author = by, url = url)
    }
    a
    • 2
    • 19
  • c

    carbaj0

    02/06/2020, 2:37 PM
    Be careful Simon, your beard is going to cover the logo :arrow:
    😂 15
    a
    • 2
    • 1
  • b

    Bob Glamm

    02/08/2020, 4:28 AM
    ORMs aren't really compatible with functional programming, if you're referring to the property where modifying fields "automagically" persists the object to the database
    t
    • 2
    • 1
  • m

    mattmoore

    02/08/2020, 4:38 AM
    Hi Daniel! I am also working with Arrow and Ktor. Bob is right, ORMs are tough to get to work with pure FP, but there are some ways to make this work. I can help you get things kickstarted if you're interested. I should have some time in a couple of days. Feel free to reach out.
    😍 2
    a
    t
    • 3
    • 7
  • p

    pakoito

    02/08/2020, 2:27 PM
    what is
    body
    here?
    g
    • 2
    • 4
  • p

    pakoito

    02/08/2020, 5:11 PM
    so check the signature, Item::class is not a ServerResponse::class
    g
    • 2
    • 8
  • p

    pakoito

    02/10/2020, 3:00 PM
    my current advice is to use the load/unload module feature
    t
    • 2
    • 5
  • b

    Bob Glamm

    02/10/2020, 3:03 PM
    I went to the dark side and explored Scala + Cats & company for the past couple of months, and VSCode + Metals is pretty nice
    h
    • 2
    • 1
  • k

    kyleg

    02/10/2020, 5:16 PM
    If I have a
    StateT<ForIO, X, Y>
    used to help manage state in my app, what is the benefit over a reader? when you
    .runM(IO.monad(), currentState)
    it yields `(newState, someVal)`wrapped in
    IO
    . I’ve been managing state in my Android app with a
    private var
    data class in my ViewModel representing a state object. For
    Id
    operations, I can just use
    State<MyState, Unit>
    to get back
    (newState, _)
    and then
    myState = newState
    . No problem. But if I’m working with
    StateT<ForIO, MyState, Unit>
    , it seems there could be race conditions doing it this way if two different state transformations are running in parallel since they’re both
    IO
    . So I can’t just
    .unsafeRunAsync { … state = newState }
    Instead, I can have these be
    StateT<ForIO, MyState, SomePartialStateChange>
    and then take the partial state change and use that to update the viewmodel’s state outside the state transformation rather than reassigning the viewmodel’s state to the transformation’s returned
    MyState
    . But at that point, why not just use
    ReaderT<ForIO, MyState, SomePartialStateChange>
    ? What’s the use case for
    StateT
    if not for this example of
    IO
    -wrapped state modification?
    p
    b
    • 3
    • 22
  • p

    pakoito

    02/11/2020, 2:21 PM
    .effect
    g
    • 2
    • 10
  • g

    Gopal S Akshintala

    02/11/2020, 5:02 PM
    How can I use
    IO
    with Spring-boot for asynchronous servlets, just like returning a
    CompletableFuture
    from a REST Controller in Spring-boot?
    p
    b
    +2
    • 5
    • 28
  • t

    TormentedDan

    02/11/2020, 7:51 PM
    noobie question here, what's the recommended way to combine different monads. Say you have 3,4 methods each returning different Kind<F,A>, what's the best syntax to merge them to another Kind?
    b
    k
    j
    • 4
    • 17
  • k

    kyleg

    02/12/2020, 4:45 PM
    What’s the best way to use
    IO.parMapN
    such that I jump back into a differnet coroutinecontext after the parallel operations have completed?
    IO.parMapN(IOThread, someIO, anotherIO) { a, b ->
      continueOn(MainThread)
      // do stuff
    }
    Does not appear I can call
    continueOn
    inside
    parMapN
    . I tried
    IO.parMapN(…).continueOn(MainThread)
    but that doesn’t seem to actually switch me correctly. I actually have
    ReaderT { 
      ... IO.parMapN(IOThread, ...).continueOn(MainThread)
    }.run(context).fix().unsafeRunAsync {
      it.fold({}, { myLiveData.value = it })
    }
    and Android throws, telling me I can’t call
    setValue
    from a background thread. So the
    continueOn
    doesn’t seem to change the coroutine context back to the main thread that way.
    • 1
    • 1
  • k

    kyleg

    02/12/2020, 11:21 PM
    Are there unchecked casts in how monad fx operates? I’ve run into an issue where (in summary)
    OptionT.fx {
      val x: Foo = OptionT(getFoo()).bind()
      val y: Bar = OptionT(getBar()).bind()
    }.value().fix().unsafeRunAsync {}
    errors out at
    val y = …
    saying cannot cast
    Foo
    to
    Bar
    . There’s no compile-time error,
    getFoo(): IO<Option<Foo>>
    and
    getBar(): IO<Option<Bar>>
    Furthermore, for the exact same user input on the exact same data set, it only occurs sometimes.
    getFoo
    and
    getBar
    wrap DB calls that return
    Foo?
    and `Bar?`` to make them
    IO<Option<Foo/Bar>>
    Might be my last question for a while! Tomorrow I go pick up a laptop from a client and boss has been joking that I’m going to be putting on 60 hours a week for a while on a project, and I have a baby due in a week. 😄 God willing, work and the baby are both chill.
    p
    • 2
    • 10
  • d

    Dasyel Willems

    02/13/2020, 10:14 AM
    Found it, thanks!
    k
    • 2
    • 1
  • d

    Derek Towriss

    02/13/2020, 8:02 PM
    Hey new to the channel and arrow. Let's say that I have ValidatedNel<Error, ValidatedNel<Error, T>>. How can I convert that to ValidatedNel<Error, T>?
    👋 1
    p
    • 2
    • 10
  • s

    Satyam Agarwal

    02/14/2020, 12:48 PM
    Hei. I don’t know if its the right channel, but here it is : 1. When can we expect to have another release in helios, as the currently released version is pointing to 0.9.0. 2. A stupid question, Can some one help me explain this graph (is more score good or is it the opposite) :
    r
    • 2
    • 2
  • g

    Giorgio Antonioli

    02/14/2020, 5:17 PM
    Hi, I'm using Arrow Optics and I'm trying to modify the items of a list based on the list's index. In pseudo code (I even tried with
    FilterIndex
    without succeeding):
    val lens = MyClass.listProperty
                  .every(ListFilterForIndex { index -> index % 2 })
                  .itemProperty
    var myObject = MyClass()
    myObject = lens.modify(myObject) { "modified string" }
    r
    p
    s
    • 4
    • 8
  • j

    Jannis

    02/15/2020, 12:17 PM
    Because
    List.map
    from the kotlin stdlib is an inline function and thus allows suspend functions inside of it if the scope from which it is called allows it.
    Option.map
    and pretty much all other arrow functions are not inline and thus don't allow it. Not entirely sure what the design decision is, but that is the reason this does not work ^^
    ☝️ 2
    g
    • 2
    • 14
  • s

    simon.vergauwen

    02/15/2020, 12:19 PM
    Yes,
    traverse
    is absolutely what you want here. Not
    map { !otherCode() }
    g
    • 2
    • 2
Powered by Linen
Title
s

simon.vergauwen

02/15/2020, 12:19 PM
Yes,
traverse
is absolutely what you want here. Not
map { !otherCode() }
g

Gopal S Akshintala

02/15/2020, 12:29 PM
I tried this, but not working out, what am I doing wrong?
private fun optionMapper() = fx.monad {
        getOptionString().traverse(Option.monad()) { booleanInput(!getIsSomethingTrueInHigherKind(it)).toOption() }}
@Jannis
View count: 2