is there a way to cache the map function of a flow...
# getting-started
a
is there a way to cache the map function of a flow for distinct events so it doesn’t recompute for the same value?
Copy code
flow(1, 1, 2, 2, 3).map { expensiveMapping(it) }.collect()
i
1. I think you don't need the return. 2. I guess you can wrap the implementation of expensiveMapping with something that memoizes the result.
a
updated for 1 🙇 like saving it at a map? That’s our current solution, but I’m not sure it’s thread safe. The flow could be updated from different threads
i
Well, you can use a thread safe map. Are you actually asking if there's a builtin caching mechanism for flow?
a
Yes, basically. Mainly because of this comment when using DataStore on Android
Copy code
Do not layer a cache on top of this API: it will be be impossible to guarantee consistency.
* Instead, use data.first() to access a single snapshot.
I want to follow it but the map is doing cryptography, and it’s expensive to decrypt the value every time.
i
Got it. I am not sure how to do it.
a
thanks for your insights anyway 🙂
h
Don't you just need to use
distinctUntilChanged
?