A very short article on different ways to do subsc...
# feed
a
A very short article on different ways to do subscription on changes: https://dev.to/altavir/to-flow-or-not-to-flow-message-subscription-in-kotlin-57ea
👍 1
p
the non-flow version can be improved by returning something like a
Disposable
that handles unsubscribing. So
Copy code
fun MyStructure.onChange(block: MyStructure.(Key) -> Unit): Disposable

val disposable = myStructure.onChange { key ->
  println(get(key))
}

disposable.close()
That brings it closer to the Flow version, makes it more convenient/somewhat less likely that you’ll forget unsubscribing, and makes the key used to track subscription identity an internal detail of
MyStructure
.
a
It is possible. But I like the variant with owner better. In this case you do not have to remember the handle. And important detail about
Flow
variant is that in general you do not have to bother since the lifecycle is handled by the CoroutineScope.
p
well, either you have to remember the handle, or the owner and to unsubscribe using the owner blob shrug 🙂 I do agree that structured concurrency/auto-cancellation is a very powerful property though. Even though I think that the ‘disposable’ version is harder to get wrong, it’s still easy to get wrong. Leaking subscriptions to stuff can be a big problem especially in larger apps.
a
Thanks for the comment anyway. The main point is that one have to remember to unsubscribe. Providing the scope for coroutines could be tiresome, but it forces you to think about the lifetime.
👍 1