Menu

LiveData vs Flows
πŸ–ΌοΈ

LiveData vs Flows

DEV CommunityΒ·Kouki BadrΒ·6 months ago
#s47zItJX
#kotlin#android#mobile#software#livedata
Reading 0:00
15s threshold

A modern mobile application is expected to be as reactive as possible, otherwise it will lag behind other apps and users won't find it attractive.

For this, the Kotlin team has provided many tools and APIs like Flows and LiveData.

If you develop Kotlin apps, you already know LiveData (otherwise, we'll judge you πŸ˜„). LiveData is a stream of data that lets developers implement a reactive flow between a producer (the class that emits data) and its consumers. But this definition also applies to StateFlow and SharedFlow β€” so what is the difference between them?

Initialization

The first difference is how we initialize both classes.

With LiveData, no initial value is required:

private val _myData = MutableLiveData<Int>()

Meanwhile, StateFlow requires an initial value:

private val _myData = MutableStateFlow < Int ?>( null ) private val _myData = MutableStateFlow < Int >( 0 )

Enter fullscreen mode

Exit fullscreen mode

The examples above show a direct translation from LiveData to StateFlow β€” you either make…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.