https://kotlinlang.org logo
Docs
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
  • s

    stojan

    05/09/2020, 8:55 AM
    to do an API call with timeout I would race it with `IO.sleep`:
    val callWithTimeout: IO<Model> = IO.raceN(
                IO.effect { service.getModel() },
                IO.sleep(2.seconds)
            )
    right?
    ➕ 2
    s
    s
    • 3
    • 5
  • n

    Nico

    05/09/2020, 6:58 PM
    Given that the draft of the KEEP I proposed got some people interested and some showed strong support, I decided to make a formal submission! You can find it here. I updated it with some suggestions and concerns some of you pointed out, and discussed some possible solutions. Pattern matching is a huge feature, so contributions are welcome and make sure you show your support! (or lack thereof!)
    ❤️ 4
    👏 11
    r
    s
    +3
    • 6
    • 200
  • h

    Hiosdra

    05/09/2020, 10:28 PM
    Hi, it’s me once more 😛 As I am writing https://github.com/arrow-kt/arrow-integrations/pull/28, I simultaneously write code for my sample arrow project and encountered case. Do you know if there is any way to “hack” this, or another contrubution 😄 is needed 😛 More will be in comment not to throw too much code in here 😛
    p
    • 2
    • 10
  • s

    stojan

    05/10/2020, 8:47 AM
    when using IO, in an
    fx
    block I can use
    continueOn
    with
    <http://dispatchers.io|dispatchers.io>()
    but also
    <http://Dispatchers.IO|Dispatchers.IO>
    or I can mix is there a preferred way? is there any difference between the two? (I am also using the coroutines integration to run the IO)
    IO.fx {
                effect { _viewState.postValue(ViewState.Loading) }.bind()
                continueOn(dispatchers().io()) // dispatchers from IO
                val repositoryDto: RepositoryDto = effect { service.getRepository() }.bind()
                continueOn(Dispatchers.Default) // Dispatchers from Coroutines
                ViewState.Content(repositoryDto)
            }
    s
    • 2
    • 6
  • s

    stojan

    05/10/2020, 8:54 AM
    second question:
    val backgroundTask = IO.fx {
                effect { Timber.d("starting sleep...") }.bind()
                sleep(10.seconds).bind()
                effect { Timber.d("sleep ended...") }.bind()
                raiseError<Unit>(Throwable("Bang!!")).bind()
            }
    
            IO.fx {
                effect { _viewState.postValue(ViewState.Loading) }.bind()
                continueOn(Dispatchers.Default)
                backgroundTask.fork().bind()
                ViewState.Content(GithubService.model) // show static data
            }
                .handleError { ViewState.Error(it.errorMessage()) }
                .flatMap { IO.effect { _viewState.postValue(it) } }
                .unsafeRunScoped(viewModelScope) { }
    if my
    ViewModel
    gets destroyed here, the
    backgroundTask
    continues executing (as expected). However after is done, the error is swallowed. Is that the expected behavior? 🤔
    s
    • 2
    • 17
  • s

    stojan

    05/10/2020, 7:26 PM
    Examples of using Arrow-Fx :arrow: on Android https://github.com/LordRaydenMK/Android-Fx-Examples inspired by this repo about Coroutines on Android -> https://github.com/LukasLechnerDev/Kotlin-Coroutine-Use-Cases-on-Android It's still a WIP, some of the examples lack descriptions but I wanted to share..... any feedback is welcomed
    😍 3
    👏 1
    p
    r
    • 3
    • 12
  • d

    Dennis Tel

    05/11/2020, 12:11 PM
    Hi! what is a good way to start with FP/Arrow? I tried performing a list of validation functions on an object before storing it in the database but quickly ran into issues trying to understand Applicatives when using Validated so looking to expand my knowledge.
    🎉 1
    👍 1
    a
    s
    i
    • 4
    • 10
  • e

    Egor Trutenko

    05/12/2020, 11:31 AM
    Obvious offtop, but where can I ask about https://scala-android.org which now apparently seems abandoned?
    r
    • 2
    • 5
  • k

    kluck

    05/13/2020, 8:01 AM
    Hi! I don't know yet the abstractions in arrow to achieve what I'm trying to do. Basically, I'd like to do some switchMapping. Here's a very simple example of what I'm trying to do:
    fun <T, E> IO<T>.setState(handleError: (Throwable) -> E, onSuccess: (T) -> IO<Any>) = IO.fx {
            val state = !this@setState.attempt()
            state.fold(
                { handleError(it) },
                {
                    // Other stuff happening…
                    !onSuccess(it)
                }
            )
        }
    
        @Test
        fun test() {
            val handleError = { t: Throwable -> println("Error: ${t.message}") }
            val onSuccess = { bool: Boolean ->
                IO.fx {
                    println("Starting")
                    !effect { delay(5000) } // --> SwitchMapping should happen around here
                    println("Finished with value $bool")
                }
            }
            // Here, this is what I don't know how to "Observablify" to send multiple events
            IO.just(true).setState(handleError, onSuccess).unsafeRunAsync {}
            IO.just(false).setState(handleError, onSuccess).unsafeRunSync()
        }
    What I expect is:
    Starting
    Starting
    Finished with value false // The other one should be "switchMapped"
    I don't know how to have some kind of flow or observable with arrow, and I don't know how to switch map within it. Any guidance?
    p
    • 2
    • 13
  • t

    than_

    05/13/2020, 8:54 AM
    Hi, I have a structure
    ListK<MapK<String,ListK<String>>>
    (don't ask 😄 ) and I need to populate it by folding some stream of data. To preserve my sanity I'd like to use optics. Basically what i need to do is to append elements to the inner lists. How would I go about doing that?
    p
    • 2
    • 3
  • k

    kobby

    05/13/2020, 8:59 AM
    I keep getting
    Cannot access Arrow.Kind which is a supertype of arrow.core.Either.Right
    I'm using arrow-core 0.10.5, arrow-core-data 0.10.5, arrow-effects-data 0.9.0
    a
    h
    p
    • 4
    • 8
  • k

    kobby

    05/13/2020, 9:30 AM
    I have a suggestion for the Arrow documentation: Would it be easy or useful to have the package next to the typeclasses being described... for example
    Either (found in arrow.core)
    this way when people read the documentation and want to try out stuff they know what to import?
    👌 6
    a
    • 2
    • 2
  • r

    renghen pajanilingum

    05/14/2020, 6:38 PM
    val result = runBlocking { parse("1") } val resultFx = IO.fx{ !effect{ parse("werew")} // an exception into an effect }.unsafeRunSync()
    p
    • 2
    • 17
  • r

    renghen pajanilingum

    05/14/2020, 6:38 PM
    suspend fun parse(str: String): Either<String, Int> =
        Either.catch { str.toInt() }.mapLeft { "wrong string value" }
    p
    • 2
    • 1
  • r

    raulraja

    05/15/2020, 7:55 PM
    Union types taking shape in the IDE https://kotlinlang.slack.com/archives/C0B9K7EP2/p1589572019120700?thread_ts=1589398414.110200&amp;cid=C0B9K7EP2
    ❤️ 12
    j
    b
    • 3
    • 19
  • s

    Saša Šijak

    05/16/2020, 4:45 AM
    IO.unsafeRunSync
    has this in the comment above it
    * **NOTE** this function is intended for testing, it should never appear in your mainline production code!
    Why is that. How would you implement the case where in a typical web app I have the following: api request -> http handler triggered -> it calls the service method -> service method calls DB service And I want to wrap the call to the DB service in the equivalent of
    Try {
      //db call here
    }.toEither {
      //handle db errors
    }
    I want to use Either early and at the boundary of my core logic, so I can model my function returns and errors as I want and translate exceptions to my errors. Also I am not running in the coroutine context. For example, stack is http4k, jooq
    s
    s
    +2
    • 5
    • 6
  • g

    georg

    05/17/2020, 5:06 PM
    Is it possible to change the kind of a Monad? Let’s say I have
    Kind<F, A>
    and I want a function that turns it into
    Kind<G, A>
    . Or even to
    Kind<G, B>
    p
    j
    r
    • 4
    • 7
  • m

    Maciek

    05/18/2020, 6:04 AM
    Noob question. I'm getting
    Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope
    when trying to run suspending function inside
    Option.fx {}
    lambda. Option itself is also in suspending function. Can't really wrap my head around why compiler doesn't allow me to run my suspending function in
    Option.fx {}
    suspending lambda
    s
    • 2
    • 3
  • r

    raulraja

    05/18/2020, 2:54 PM
    For those interested in the new type system features that Meta will offer a la carte https://kotlinlang.slack.com/archives/C1JMF6UDV/p1589810902095200
    :arrow: 7
    👍 3
    🙌 4
    c
    • 2
    • 1
  • j

    julian

    05/18/2020, 8:05 PM
    What does
    <ERROR CLASS>
    in the docs mean? Is it a glitch in the docs generation? For example:
    tailrec fun <L, A, B> tailRecM(a: A, f: (A) -> Kind<<ERROR CLASS><L>, Either<A, B>>): Either<L, B>
    r
    r
    • 3
    • 10
  • s

    simon.vergauwen

    05/19/2020, 8:48 AM
    Yes, that is exactly one of the great usages of
    Union
    . You can compose 2 errors together, without having to create a new ADT that wraps the errors.
    😍 3
    c
    • 2
    • 1
  • s

    Satyam Agarwal

    05/20/2020, 10:37 AM
    okay I seee :
    fun NonFatal(t: Throwable): Boolean =
      when (t) {
        is VirtualMachineError, is ThreadDeath, is InterruptedException, is LinkageError -> false
        else -> true
      }
    r
    • 2
    • 12
  • p

    pakoito

    05/22/2020, 2:07 PM
    they’re not
    d
    • 2
    • 6
  • s

    Satyam Agarwal

    05/23/2020, 5:53 PM
    That can explain why I loose my MDC context for the logs that are wrapped inside effect
    d
    • 2
    • 2
  • t

    tim

    05/24/2020, 1:18 PM
    Hi folks, I'm just discovering FP & arrow and I'm very excited! I have limited experience with FP. I understand some of the basics, I've read lots, I've used HOCs, compose, I get pure vs effects, etc. Most of my experience comes from redux and react. However, i have never put together a large application following FP principles. I'm starting a new project this week and I'd like to try a functional-first approach as much as possible. It's a ktor & graphql based micro service that will serve as the backend to a web-based UI. Nothing too fancy. So my question, are there good example applications which are considered best practice to use as a template? I have very basic unknowns which could be answered with an example... How often are classes and FP mixed? How is functional only code organised? By package, inside singletons, etc etc. I appreciate that a lot of the answer depends but still keen to explore an example. 🙏 🙏
    s
    • 2
    • 4
  • s

    stojan

    05/25/2020, 6:19 PM
    let's say I have a
    UserServiceAlgerbra
    for working with users.... If I use
    suspend
    for my methods (instead of
    IO
    ), what would be the equivalent of
    raiseError
    in case of duplicate users for
    suspend fun createUser(user: User): Unit
    ?
    p
    • 2
    • 1
  • c

    CLOVIS

    05/25/2020, 6:36 PM
    From what I understand of KEEP-87, the objective is to give the possibility to make an object implement an interface from outside the object itself, allowing users to make classes they don't control implement behavior they want, such as
    Comparator
    and similar behavior interfaces (which are called ‘Type classes'? Please correct me if I'm wrong). It would also allow to implement a behavior in different ways, and choose which behavior is used when calling a function (with an explicit
    with
    parameter), which makes dependency injection trivial (possibility to implement patterns such as DAO with some nice syntax sugar).
    ✔️ 1
    r
    • 2
    • 8
  • c

    carbaj0

    05/26/2020, 9:49 AM
    Hello! I have a little doubt. When I try to modify a field Option <String>, this is replaced by a String instead of a Option<String>
    ej : data class PersonalDataModel(
        val firstName: Option<String>
    )
    
    firstName.modify(state){ //here i have a String instead of Option<String> }
    s
    • 2
    • 8
  • t

    tim

    05/26/2020, 8:57 PM
    Hello, I'm tinkering with arrow.fx. I'm exploring the Effect and Fibers and I'm struggling to understand what the difference is between ... other than one runs quicker than the other! I'm a few days into arrow so apologies I'm if doing something that doesn't make sense or if my code below is naive 🙂 To explore, I've written the following functions:
    fun doWorkWithIO() {
            val time = measureTime {
                IO.fx {
                    val effects = mutableListOf<Kind<ForIO, Int>>()
                    for (i in 0..1_000_000) {
                        val thing = effect { i }
                        effects.add(thing)
                    }
                    effects.forEach { it.bind() }
                }.unsafeRunSync()
            }
            println("Default IO took $time")
        }
    
        fun doWorkWithFork() {
            val time = measureTime {
                IO.fx {
                    val effects = mutableListOf<Fiber<ForIO, Int>>()
                    for (i in 0..1_000_000) {
                        val thing = effect { i }.fork().bind()
                        effects.add(thing)
                    }
                    effects.forEach { it.join() }
                }.unsafeRunSync()
            }
            println("Fibers took $time")
        }
    doWorkWithIO
    completes in about 1 second and
    doWorkWithFork
    runs in about 3 seconds. Are fibers using coroutines under the hood or threads? If so, whats the difference between them and effect? I assume they're for different things otherwise the wouldn't exist 🤷‍♂️ Is my code completely wrong!?
    p
    • 2
    • 5
  • b

    Bob Glamm

    05/26/2020, 9:28 PM
    My understanding: fibers and effects both use suspend functions. Fibers can be launched into coroutine scopes/pools for parallel execution. I expect that
    doWorkWithFork
    takes longer purely due to the overhead of launching suspend functions into coroutines. If your effect body does something computationally intensive or takes time - a simple example is to delay 5 seconds - then you should see
    doWorkWithIO
    take more total time than
    doWorkWithFork
    . (Change the upper limit to 10 or 20 instead of 1,000,000 if using a five-second delay.)
    👍 1
    t
    • 2
    • 1
Powered by Linen
Title
b

Bob Glamm

05/26/2020, 9:28 PM
My understanding: fibers and effects both use suspend functions. Fibers can be launched into coroutine scopes/pools for parallel execution. I expect that
doWorkWithFork
takes longer purely due to the overhead of launching suspend functions into coroutines. If your effect body does something computationally intensive or takes time - a simple example is to delay 5 seconds - then you should see
doWorkWithIO
take more total time than
doWorkWithFork
. (Change the upper limit to 10 or 20 instead of 1,000,000 if using a five-second delay.)
👍 1
t

tim

05/26/2020, 9:38 PM
Thanks for this. I'll try it out tomorrow
View count: 2