https://kotlinlang.org logo
#coroutines
Title
# coroutines
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
Copy code
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
Copy code
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
Copy code
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
Copy code
// 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:
Copy code
// 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)
5 Views