I'm wondering if there's such a pattern in Resourc...
# arrow
d
I'm wondering if there's such a pattern in Resource: Say I need to register listeners and callbacks on another "mother" resource and when closing down the "mother" have all the children unregister before they get closed too. Is this currently possible?
y
This should just naturally happen:
Copy code
resourceScope {
  val mother = install(...)
  val child = makeChild()
  mother.registerChild(child)
  onRelease { mother.unregisterChild(child) }
}
The child will be unregistered first, and then the mother resource will get closed down
d
But then I need to have all the children in the mother resource scope which could get unwieldy when there are quite a few, it might have been nice to be able to compose resources (have one resource depend on the lifecycle of another and receive the "mother" in it's onRelease to be able to release itself). Basically it's about decoupling things that aren't supposed to be so coupled, since a mother can always be created w/o listeners, but sometimes listeners need to be added with their lifecycle handled...
y
All the children depend on the mother's lifecycle, no? So it makes sense that they'd depend on its resource scope
d
I see in your code, you have the mother's instantiation decoupled, but in the end all the listeners will need to be in that same resourceScope block...
Copy code
resourceScope {
  val mother = install(...)
  val child = makeChild()
  mother.registerChild(child)
  val child1 = makeChild1()
  mother.registerChild(child1)
  ...
  onRelease { 
    mother.unregisterChild(child) 
    mother.unregisterChild(child1) 
    ...
  }
}
I'd like to have each child manage itself, and compose with the "mother"
y
You can have
makeChild
take in the ResourceScope, and thus the child will be closed. Then, have
registerChild
also take it in and automatically unregister the child too.
d
It doesn't seem like there's any onClosing for side-effects from a resource?
y
onRelease
does that, but there's also
onClosed
I think which comes from
AutoCloseableScope
(which
ResourceScope
inherits)
d
I guess I'm not too clear on how this would look in the end... I'm really just starting to try out Resources a bit more than before... could you maybe just sketch out how you're picturing it please? Thanks for you time!
@Youssef Shoaib [MOD] Here's my real use-case, how do I split this up into smaller more decoupled pieces?
I'd like things like
fixBehindLiveWindowPlayerListener
and
imaAdsLoader
to handle their own lifecycle, also I'd only like to initialize an imaAdsLoader if playAudioAds is true...
I have more listeners, and I keep on adding and removing some, and I really don't want to forget to manage their lifecycles... (I'm doing a bunch of testing on variations...)