Last active
December 19, 2018 11:28
-
-
Save lookashc/31fa1b80fa2bbd7ec28dd7f3c6cee88e to your computer and use it in GitHub Desktop.
Simple wrapper over MediatorLiveData to build relations between LiveDatas in Android ViewModels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun <T> dependantLiveData(vararg dependencies: LiveData<*>, crossinline mapper: () -> T?) = | |
MediatorLiveData<T>().also { mediatorLiveData -> | |
val observer = Observer<Any> { mediatorLiveData.value = mapper() } | |
dependencies.forEach { dependencyLiveData -> | |
mediatorLiveData.addSource(dependencyLiveData, observer) | |
} | |
} | |
//Example usage | |
class UserViewModel(private val resourceProvider: ResourceProvider) : ViewModel() { | |
val firstName = MutableLiveData<String>() | |
val lastName = MutableLiveData<String>() | |
val displayName = dependantLiveData(firstName, lastName) { | |
resourceProvider.getString(R.string.display_name, firstName.value.orEmpty(), lastName.value.orEmpty()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment