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
hiring-french
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
f

frankelot

05/12/2021, 1:55 PM
Hi All! 👋 I'm wondering if this is OK
I'm wondering because I'm not explicitly calling 
coroutineContext.cancel()
 anywhere
I figure the garbage collector will eventually get rid of it
I'm wondering because I'm not explicitly calling 
coroutineContext.cancel()
 anywhere My current architecture uses reusable custom views
should I instead pass the parent Activity/Fragment Scope parmeter?
a

Adam Powell

05/12/2021, 2:07 PM
you don't have a
Job
in the coroutineContext so trying to cancel the context won't do very much for you
being attached to a window doesn't mean the view is visible. That flow collection will still run while the host activity is behind another activity in your app, while your app is in the background, or even while the screen is off in some circumstances. It's unlikely this is what you want
by giving a CoroutineScope to a View you've given that view more lifecycle responsibilities. Views tend to have enough responsibilities - accepting user input, measure/layout, drawing - it's often easier to keep the view subclasses simpler and have the code that assembles your layout establish the binding and the lifecycle of that binding as a layer above the view
l

louiscad

05/12/2021, 2:13 PM
FYI, it's not recommended to implement
CoroutineScope
on your own because it can lead to easily launch in the wrong scope later on. Best to have it be a property for the cases where you need it.
a

Adam Powell

05/12/2021, 2:16 PM
yeah that too, in particular a private property so that other code doesn't get into the habit of launching arbitrary jobs into your scopes.
1
The
ViewModel.viewModelScope
extension set an awful precedent for this; its nature as an extension to a library written in the java language forced it to be public when it really shouldn't have been
that was a compromise, not design intent 🙂
l

louiscad

05/12/2021, 2:19 PM
Should've been
protected
, right?
a

Adam Powell

05/12/2021, 2:22 PM
perhaps, but arguably I think it shouldn't have existed at all. creating a scope manually and cancelling it in
onCleared
is a pretty small inconvenience in those cases where you have an AAC ViewModel that really needs to own a CoroutineScope; many don't. The existence of
viewModelScope
terminates further thought about whether an operation should be scoped to the UI or to a repository.
l

louiscad

05/12/2021, 2:23 PM
If you don't have any
ViewModel
subclasses in your app, you don't have this problem though :think-smart:
a

Adam Powell

05/12/2021, 2:25 PM
which sort of circles back to the point from above: don't create objects capable of acting autonomously within a lifecycle of their own when it's not necessary, View, ViewModel, or otherwise.
1
👍🏼 1
:blob-think-smart: 1
s

streetsofboston

05/12/2021, 2:25 PM
As a side note; I strongly discourage having ViewModels in your (custom) Views. Let Views be Views and just let them have a plain API that deals with their state modifications.
2
a

Adam Powell

05/12/2021, 2:27 PM
agreed. Kotlin extension functions are a great tool for providing a bridge/convenience for binding the contents of a viewmodel-like object to a view without the actual view subclass having to know anything about the viewmodel class's existence.
s

streetsofboston

05/12/2021, 2:28 PM
If you want testable behavior associated with a (custom) View, create a Controller, a Delegate, whatever you want to call it that is coupled to your custom View, much like a super simple, light-weight Fragment that wraps around your (custom) View. That Controller/Delegate/Wrapper could have a ViewModel, if need be. Still, consider that a ViewModel may not be necessary at all in these cases.
f

frankelot

05/12/2021, 2:52 PM
Thanks for the replies! but I'm still not sure how to proceed
my app uses custom views (no fragments) and I'd like to keep it that way
What if don't make my View a
CoroutineScope
but instead use the parent Activity scope
job = (context as LifecycleOwner).lifecycleScope.launch {}
I still create/cancel that job onAttach/onDettach
a

Adam Powell

05/12/2021, 2:54 PM
The question of how to proceed is very open-ended and subject to a lot of opinion 🙂
Downcasting your context has plenty of issues of its own, and the context involved may not be the Activity at all, it's often a ContextThemeWrapper or similar
☝️ 2
☝️🏼 1
l

louiscad

05/12/2021, 2:56 PM
Maybe you want a "view controller" that has a reference to the views, the repository(ies) or whatever, plus gets the right coroutine scope, and runs the right code.
f

frankelot

05/12/2021, 2:56 PM
I see... So this cast can potentially fail
a

Adam Powell

05/12/2021, 2:57 PM
More or less. If you don't want "Fragments" that's fine, but fragments do fill a particular niche in the stack that View subclasses are not well-suited to do on their own.
f

frankelot

05/12/2021, 2:57 PM
I can't use fragment in this scenario since this view needs to be placed inside an already existing RecyclerView
s

streetsofboston

05/12/2021, 2:58 PM
Modify your Fragment/Activity that hosts the recycler-view and let its ViewModel emit the proper data to fill the recycler-view's adapter and ViewHolders
l

louiscad

05/12/2021, 2:59 PM
This might be what you're looking for: https://github.com/yigit/suspend-bind
1
👀 1
Brought to you by The Messiah of Android
😁 2
f

frankelot

05/12/2021, 3:01 PM
Modify your Fragment/Activity that hosts the recycler-view
Right now this is a custom view that I can put anywhere, I'd like to keep it that way 🙂
s

streetsofboston

05/12/2021, 3:08 PM
Still, your Fragment/Activity that hosts your recycler-view needs to send the recycler-view the data (to its adapter) that it needs to show. This data is emitted by the Fragment/Activity's ViewModel. If your custom View in your recycler-view needs to be showing new data, update the recycler-view's adapter's data with that new data. (Tightly) coupling ViewModels with (custom) Views can get troublesome.
f

frankelot

05/12/2021, 3:10 PM
This view works on its own, does not need to be bound or provided with data. It gets injected with a Service that has Application Scope and reacts to this service stream of events (a StateFlow)
it was originally a fragment, that worked in the exact same way..
but then I turned it into a view because I needed it to be it in this recyclerview
The adapter only knows that it needs to inflate this view (or not) and in which position
but does nothing when binding this view
override fun onBindViewHolder(holder: ProfileVH, pos: Int) {
 when(holder) {
  MyCustomView -> //no op, no binding required
  ... ->
  ... ->
}
}
a

Adam Powell

05/12/2021, 3:20 PM
binding is what assigns the position. If you're doing nothing in an onBindViewHolder you're going to have issues when RV rebinds the same view instance to a different position.
f

frankelot

05/12/2021, 3:21 PM
I thought binding is what changes the contents of the view
binding is what assigns the position
😱 what do you mean by this?
s

streetsofboston

05/12/2021, 3:22 PM
If your custom View gets its own data and it gets bound to a different adapter-position, your custom View may then show the incorrect data if it doesn't get updated in the onBindViewHolder callback This happens after an recycler item-view gets recycled and re-bound to a new adapter position.
☝️🏼 1
☝️ 2
f

frankelot

05/12/2021, 3:24 PM
I think I'm good because
onViewAttached
subscribes to a stateflow that updates the data
a

Adam Powell

05/12/2021, 3:25 PM
Not if it's subscribed to the wrong data because assigning the data source was skipped during binding
☝️🏼 1
l

louiscad

05/12/2021, 3:28 PM
Using the right coroutine scope, combined with the suspend-bind library by Yigit (who worked on RecyclerView itself) is most likely the safest approach, despite the library using internal APIs in RecyclerView. I say it's safe because these APIs are quite unlikely to ever change, for backwards compatibility reasons and the fact that Compose APIs are the ones being focused on when it comes to scrolling large data sets and UI in general.
f

frankelot

05/12/2021, 3:29 PM
Not if it's subscribed to the wrong data because assigning the data source was skipped during binding
this is my view
class CustomView @JvmOverloads constructor(...) : FrameLayout {

@Inject 
lateinit var service : MyService;

overrideOnAttach() {
 job = (context as LifecycleOwner).lifecycleScope.launch {
   service.stateFlow.collect { ... }
}
}
}
🙂 there's no "wrong data", because the data is not coming from the adapter
l

louiscad

05/12/2021, 3:30 PM
You mean it's the same data for all similar items in the RecyclerView?
f

frankelot

05/12/2021, 3:31 PM
Yes.. More specifically There's only one instance of this view type in the recyclerview
the other kind of views in the adapter work in a more conventional way, they get "bound" with data on
onBindViewHolder
l

louiscad

05/12/2021, 3:33 PM
Then, it's safe if you're 100% certain there will never be another instance that expects different data in the same RecyclerView. You can skip its code in the onBind altogether.
💯 1
f

frankelot

05/12/2021, 3:35 PM
🙂 I thought so, I was afraid I had been using adapters wrong for a while LOL
I think Im going to stick with
// on Attach
job = (context as LifecycleOwner).lifecycleScope.launch {}

// on Detach
job.cancel()
😕 1
as long as the cast succeeds I should be fine
a

Adam Powell

05/12/2021, 3:37 PM
tbh what you started the thread with was better than that
f

frankelot

05/12/2021, 3:37 PM
interesting... 🤔 why?
In my original implementation, I'm creating a Scope and never calling
cancel
on it
a

Adam Powell

05/12/2021, 3:38 PM
/me looks back at the whole thread
l

louiscad

05/12/2021, 3:38 PM
It'd still be better to use the suspend-bind thing with a coroutine scope injected into the adapter @frankelot
1
f

frankelot

05/12/2021, 3:39 PM
but I'm not doing anything in bind 😄 no need to suspend @louiscad
s

streetsofboston

05/12/2021, 3:44 PM
To get the lifecycle-owner from the view's context:
// top level val
private val Context?.lifecycleOwner: LifecycleOwner? get() = when (this) {
  is LifecycleOwner -> this
  is ContextWrapper -> this.baseContext.lifecycleOwner
  else -> null
}
l

louiscad

05/12/2021, 3:45 PM
@frankelot What you'd do in that suspending bind is running the code you currently run in the
launch { … }
, i.e. collecting the
StateFlow
.
That way, you can get rid of the unsafe window attachment callbacks that are most likely not really what you want, and have edge cases.
a

Adam Powell

05/12/2021, 3:48 PM
@streetsofboston there's a great big, "it depends" around that. That won't catch the
LifecycleOwner
of any containing fragments, for example.
ViewTreeLifecycleOwner.get()
is probably more reliable but even that has its edge cases
☝️ 1
s

streetsofboston

05/12/2021, 3:49 PM
Yup; this'll only work if the recycler-view is hosted by the Activity directly.... But it's safer than just casting
context as LifecycleOwner
🙂 I never heard of ViewTreeLifecycleOwner... interesting
a

Adam Powell

05/12/2021, 3:50 PM
which is why this whole approach is unnecessarily brittle. It's not simpler to do things this way and there are edge cases that you have to have a lot of domain knowledge to be aware of.
☝️ 2
f

frankelot

05/12/2021, 4:04 PM
@louiscad that would work! but I see two drawbacks. 1 - it requires adding a library just for this one use case, 2 - The view is not reusable anymore. It requires its parent to know where to get data to feed it with
maybe that's a good thing, idk
l

louiscad

05/12/2021, 4:07 PM
The view is still reusable, you just also need to attach the right "data provider" (the stateFlow). FYI, I personally copy pasted the code of the library into my project to integrate it with some extension I made, but even adding the dependency should not be a big deal, it's a quite small library, made by someone not that random (the early leader of Android architecture components, which includes androidx.lifecycle)
f

frankelot

05/12/2021, 4:12 PM
you just also need to attach the right "data provider"
Ideally I'd like this not be the responsibility of the adapter. The adapter just knows about what views need to be laid out and in what order.
This is my idea btw, not claiming it's a good idea 😅
to give you more context, the adapter lives in a module, and the view lives in another. These modules are completely unrelated. The adapter displays lots of views... From lots of feature modules
l

louiscad

05/12/2021, 4:14 PM
The adapter has two main responsibilities constrained by its API: giving new views of a given type, and enabling/disabling views for a given position (the binding, which is cancellable with suspend-bind)
You can make the adapter delegate that work to another function or whatever you pass to it, but it's designed to be the "middlefolk" regardless.
m

myanmarking

05/14/2021, 8:24 AM
the best solution for this case, imho is: find another way. (for example, as some1 suggested, dispatch state changes to the view. Do not give it the responsibility to observe and modify state)