Is there any benefits to using LiveData rather than a regular callback?

Viewed 1267

I have an app in which the user is allowed to sign-in. The user data is saved in the database. The MainActivity implements an interface OnUserCreationCallback:

class MainActivity implements OnUserCreationCallback {
    //Unrelated code

    @Override
    void setUser(boolean created) {
        if(created) {
            //Display welcome message
        }
    }
}

Once the user is created in the database, the setUser() method fires and the user gets a welcome message. This is working as expected. My question, is there any real benefit of implementing a ViewModel and a LiveData, that can be observed when the user is created? I'm talking only for this particular operation and not for an operation that changes multiple time. It's a one time operation.

2 Answers

There's a chance this will leak your activity if you keep the callback after the activity is destroyed. For example if you keep your user repository or whatever around during configuration changes, it will keep referencing the callback, i.e. the activity, and it will never really be destroyed.

LiveData on the other hand is lifecycle aware and will be unsubscribed according to the lifecycle owner it's registered upon, for example when the activity is destroyed.

The other guy posted very good points too. This is basically the MVP vs MVVM debate.

Yes:

Livedata is life cycle aware.

That means if the fragment is detached or the user quits the app the observer is also detached.

In your case that could prevent user exiting the app and getting a null pointer exception because the host doesn't exist. In more complex cases it would help you to coordinate events better.

LiveData is a way of doing asynchronous programming, in using observers. From local db to the View you can observe a live data or use Coroutines to get the data, the result is the same and you have to judge when is better to get a result inside a coroutine or when is better to have an observer.

I'm telling the above because you don't need ViewModel, it is part of Jetpack, but if your DAO returns LiveData then you can observe that directly from the View (that would be bad architecture by the way) or you could use a Presenter.

@Dao
interface EntityDao {
      @Query(/*SELECT ALL*/)
     suspend fun getAll(): List<Entity>

     @Query(/*SELECT ALL*/)
     fun getAll(): LiveData<List<Entity>>

}

There are other inmplications, for testing live data you need to have some helper method or use espresso but for testing suspend functions you can use robo electric or the runBlockingTest suite

Related