https://kotlinlang.org logo
#coroutines
Title
# coroutines
u

ubu

06/11/2020, 4:23 PM
Hi there! Is there a way to update a
value
in
StateFlow<Map<Id, T>>
, so that current subscriber does not a receive this update? I have a particular use case from UI programming. Suppose that this
T
is
String
. We have a list of texts, that is rendered first in a text editor. This text is then edited by our user and we receive
onTextChanged(id, text)
event. We now need to sync this text change with our state:
map[id] = text
, but we do not need to render this state again, because UI already has it. Or maybe there is no way to resolve this problem with
StateFlow
?
z

zak.taccardi

06/11/2020, 4:24 PM
the problem you are describing is that the UI toolkit on Android updates itself
u

ubu

06/11/2020, 4:25 PM
yes, changes are in text widget before they are in a view model.
z

zak.taccardi

06/11/2020, 4:27 PM
my recommended solution is to not use
StateFlow<String>
for
EditText
, and let the
EditText
itself be the source of truth. If the
ViewModel
needs to update the
EditText
, then it should emit these updates as a “side effect”
u

ubu

06/11/2020, 4:36 PM
it is the source of truth when text changes, indeed. but i need to work with the objet that represents state of this text in my view model; what i need is a way to have mutual syncing…
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 4:50 PM
This can be a complicated problem, but if you’re not dealing with asynchronous updates, you can just compare the new string from your state with the current text in the view and only set it if it’s different.
👍 1
u

ubu

06/11/2020, 5:31 PM
I’m dealing also with spans, focus and diff util 🙂
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 5:44 PM
Spans & focus can be handled by calling
Editable.replace
instead of
setText
to update the text.
Diffutil should be fine, unless you’re running it on a separate thread – that’s where it gets complicated.
👍 1
z

zak.taccardi

06/11/2020, 5:45 PM
Probably pretty important to run Diffutil on a separate thread
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 6:02 PM
You can make it work, but you basically need to synchronize two concurrent state machines which is fun.
6 Views