https://kotlinlang.org logo
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
benchmarks
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
confetti
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
lincheck
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
Title
e

elizarov

06/08/2020, 9:08 AM
📣 Shootout to all Android devs using MVI, MVVM, etc with coroutines. How do you handle events that need to be processed exactly once by your views (like navigation events, etc)? That is, what approach do you use with coroutines to work around the problem explained here for LiveData: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150 0️⃣ I’m avoiding this problem altogether, not using anything like
Rx/Channel/Flow/LiveData
to deliver those events (comment in :thread-please: what you do instead). 1️⃣ Using an
Event
wrapper class, adapting solution in the above story to coroutines. 2️⃣ Using a [buffered or rendezvous]
Channel
for events, exposing it to the views either as
Channel
or as a
Flow
via
receiveAsFlow()
extension. 3️⃣ Some other approach (comment in :thread-please:).
0️⃣ 7
2️⃣ 27
3️⃣ 3
1️⃣ 26
g

gildor

06/08/2020, 9:15 AM
3️⃣ or 1️⃣ depends on how critical event is. If it have to be handled even if there are no subscribers now, then 1️⃣ is only solution (for example such cases as opening another screen or dialog asyncronously), if lost event in case of there are no subscribers is fine (like direct user interaction, like click), then 3️⃣ : so it’s just exposed as PublishSubject (so subscribers receive only new events, after subscribtion)
m

Martin Nordholts

06/08/2020, 9:16 AM
For the SnackBar use case: The
ViewModel
contains a
LiveData<MessageToShow>
field that our SnackBar implementation listens to via XML Data Binding, and clears upon close-button being clicked (also via XML Data Binding), or via timeout from within ViewModel. The field can be set via a coroutine that runs within ViewModel scope. For the “press back” use case: ViewModel is not used at all since ViewModel is about data to be displayed, which is not really related to events (although of course, an event can mutate the ViewModel data, but for e.g. a “go back” event, no ViewModel data per-se is mutated. The point is that events are not stored within ViewModel, it’s only side effects of events that are stored)
s

sindrenm

06/08/2020, 9:17 AM
We're using 1️⃣, but still with LiveData. While it would be nice to use something like a StateFlow or something instead of LiveData here, We could move to StateFlow for view state, but for events, it's more difficult. as
MutableStateFlow()
takes an initial value.
Granted, StateFlow for one-off events is probably the wrong move anyway. We didn't give it too much thought yet, unfortunately, and just stuck with LiveData for now.
g

gildor

06/08/2020, 9:21 AM
I think the fact that MutableStateFlow doesn’t have default constructor is a bit confusing. LiveData handles it by returning null from getValue() if value is not set, but at least it a bit more flexible if you don’t want emit default value
p

pawegio

06/08/2020, 9:25 AM
0️⃣ in imperative way, invoked from logic, android impl details hidden behind the interface, no state means no LiveData/BehaviourRelay/StateFlow, make it simple
3
s

sindrenm

06/08/2020, 9:25 AM
Surely, this would work if we wanted it to “be the same” as LiveData in that regard:
val viewEffects: StateFlow<Event<ViewEffect>?>
    get() = _viewEffects

private val _viewEffects = MutableStateFlow<Event<ViewEffect>?>(null)
But I don't feel like events should ever be
null
. 😛
g

gildor

06/08/2020, 9:41 AM
this would work if we wanted it to “be the same” as LiveData in that regard
LiveData doesn’t emit null if you subscribe without default value, so it’s not the same, it more like:
val viewEffects: StateFlow<Event<ViewEffect>>
    get() = _viewEffects.mapNonNull()
Tho it still looks unnecessary to do with operator
f

flosch

06/08/2020, 9:45 AM
0️⃣ since navigation is not an observable state.
👍🏽 4
🇳🇴 1
g

gildor

06/08/2020, 9:49 AM
@flosch It’s not an “observable state” but you can expose navigation events as a stream of events, exactly what Flow does, it’s very powerful, and also the only proper way to implement navigation with MVVM with detachable VM, on Android at least, but not only, when you need current screen context to do navigation, but you cannot hold reference on it
k

kenkyee

06/08/2020, 10:11 AM
For the snackbar case, you're supposed to use it in the manual show/hide mode and then you can use a LiveEvent (which really should be named LiveState). For click a button and go to a different frag/activity, I've usually hooked them up using flowbindings like you'd do with rxbindings.
s

streetsofboston

06/08/2020, 11:38 AM
2️⃣ , as a new class
EventFlow
, implementing
Flow
by a Rendezvous Channel's
receiveAsFlow()
. It has two methods/props:
CoroutineScope.value: T
(only as a setter) and
suspend fun postValue(v: T)
., both sending the providied value to the Channel.
d

Drew Hamilton

06/08/2020, 11:53 AM
I’m also using a RendezvousChannel; not sure whether that should count as 2️⃣ or 3️⃣
e

elizarov

06/08/2020, 11:56 AM
Pick 2️⃣ if you use any kind of channel
z

Zach Klippenstein (he/him) [MOD]

06/08/2020, 12:30 PM
We associate an ID with the event (eg a random UUID or monotonically increasing int), store the event in the UI's view model, and "fire" the event by changing the ID. The consuming view is expected to track this ID over time and detect when it changes. This is rare though, our navigation is state-based, not event-based, and we try to push as much code as possible to be state-based, so the toast/snackbar example is I think only case, or at least the main case, where we need this.
d

dewildte

06/08/2020, 12:53 PM
Collect the
Flow
of events and stop collecting when the
LifecycleOwner
is not in the correct state for handing the event.
a

Adam Powell

06/08/2020, 1:38 PM
Fwiw the reason this article exists is because
LiveData
is a state type, not an event stream type. 1️⃣ is a hack to work around this without sorting out the difference between events and state in the app, which has been pretty harmful to the understanding of the whole space for a lot of people since it was written.
💯 1
h

henrikhorbovyi

06/08/2020, 1:56 PM
@gildor You said: expose navigation events as a stream of events - Can you show some article or project implementing it? I've never used this approach 🙂
g

gildor

06/08/2020, 2:20 PM
@henrikhorbovyi You may check an article mentioned by Roman in his message, it show example of this approach. Essentially when navigation events exposed as stream of events when view subscribes on those events and dispatch them
👍 1
r

rkeazor

06/08/2020, 3:20 PM
Event wrapper with livedata is what I see in majority of code bases... channels i would think is more tricky based on the different lifecycles
h

henrikhorbovyi

06/08/2020, 3:39 PM
I was confused about this discursion before 😄 But now I got the point. I agree @rkeazor
d

dewildte

06/09/2020, 1:13 PM
@Adam Powell Why can't we pull that dang article down?
a

Adam Powell

06/09/2020, 1:28 PM
I think I've been having that discussion with Jose on and off for two years now 🙂 when it was posted Flow wasn't in the picture as a stable API and the alternative to recommend would have been RxJava, and even now the wider Android developer community is still wrapping their heads around coroutines conceptually. It's a lot to ask people to learn, and that post offered a quick band-aid instead.
d

dewildte

06/09/2020, 1:56 PM
A quick fix for a war time wound left un-attended can lead to sepsis. 😁
b

Brendan Weinstein

06/11/2020, 6:59 PM
Re: Roman's original question I use two channels between view<->viewmodel: one for state and one for ephemeral events. ephemeral events: navigation, toasts, alerts, transitions https://github.com/kaushikgopal/movies-usf-android -- is a good example.