Member-only story
No More LiveData in Repositories in Kotlin
Learn how to replace LiveData with Kotlin Flow
What Is LiveData?
We can describe LiveData as an observable data holder class, meaning it can hold a set of data that can be observed from other Android UI components such as activities, fragments, and services.
LiveData is lifecycle-aware. Once the component that is observing data is destroyed or not active, LiveData stops publishing data to that observer. This solves many common problems for Android developers.
Most developers use LiveData in an MVVM architecture to communicate or transmit data from the ViewModel to the view. This ensures lifecycle-aware communication between them by reducing memory leaks.
But there are cases where I saw developers use LiveData to communicate between a repository and a ViewModel, including a Google I/O application. Using LiveData in this case seems correct. After all, it’s designed to hold and pass the data. But it’s not recommended, and you’ll learn why in the following sections.
Advantages of using LiveData:
- No memory leaks
- No crashes due to stopped components
- No more manually lifecycle handling
- Resource sharing
What Is Kotlin Flow?
Before coroutines, most developers used RxJava for asynchronous programming. When Kotlin came up with coroutines, developers loved them. They solved all the traditional problems with async programming in a more sophisticated way than RxJava.
Before coroutines, we had to call an asynchronous function like a service call, retrieving data from the database, reading files, or anything via callback. We could only resume the actual work when we knew that the operation was finished, like mobiles updating the UI after receiving data from your servers.
Coroutines offer a solution to this through suspend
functions. Suspend
functions can suspend the execution of the current thread until the job is completed. Have a look: