I haven't really kept up to date with flow as a re...
# android
c
I haven't really kept up to date with flow as a replacement for LiveData. I use LiveData currently to connect my AAC ViewModel to my Fragment. I looked up some quick articles and it seems like I would replace my LiveData usage of:
Copy code
private val _name = MutableLiveData("")
   val name: LiveData<String> = _name
with StateFlow like this
Copy code
private val _name = MutableStateFlow("")
    val name: StateFlow<String> = _name
Is that pretty much it? I do plan on reading/learning more about it, but I'm just trying to get a POC done and just wanted to make sure I'm not breaking any rules here that I don't know about. Cheers
a
That's basically it. If you look at the recent alphas of the lifecycle-runtime artifact you'll see some things like repeatOnLifecycle and flowWithLifecycle that do some bridging between structured concurrency and the LiveData-like behavior you might be used to
But those are more useful for cold flows. Hot multicast observables like that are a slightly different beast
c
Yeah, from what I've seen liveData still has "better" support for auto subscribing/unsubscribing due to my fragment lifecycle. Because of that actually... I think I'll stick to LiveData. I think the only real benefit I noticed from StateFlow is that it can't be null.
t
Beware that there's a huge difference between those 2. StateFlow won't emit if you update with the same value while live data will. Depending on what you do this can be a problem.
j
@Colton Idle if that is the only reason then perhaps you can use the new lifecycle extension functions. Flows you can use in any layer in your app, of course it is easy to use livedata in the last step but I think it is rather unnecessary, just collect the flow using extension functions on viewLifecycleOwner and it is as safe as livedata.
1
c
@Joost Klitsie I had not heard of the new lifecycle extension until Adam powell mentioned it above. Will have to look into it!
a
LiveData notifying observers if an equal value is set is broken. An observer relying on that behavior means that observer is also broken. State observers should always be idempotent, otherwise your observable isn't really state, it's an event stream, and LiveData is not fit for purpose as an event stream for many reasons.
j
What you're saying is the thing it should do it doesn't do properly, and the thing it actually does, it doesn't do well :D
a
Yes. 😄
The only reason to use LiveData in 2021 is for local consistency with surrounding code.
c
Hm. Maybe I'll go with StateFlow then... 😅 I guess I just like the lifecycle awareness of LiveData, but as you all have pointed out, there is a new extension function for that so I will have to try that. Maybe there will be some session at I/O that talks about those new extensions.