Skip to content

Instantly share code, notes, and snippets.

@ShinichiroFunatsu
Created November 11, 2018 15:38
Show Gist options
  • Save ShinichiroFunatsu/ea08b05573420e4925405852947f2b5f to your computer and use it in GitHub Desktop.
Save ShinichiroFunatsu/ea08b05573420e4925405852947f2b5f to your computer and use it in GitHub Desktop.
Reactive Sample with Live Data
class InputConfirmViewModel : ViewModel() {
// inputs
val inputStream = MutableLiveData<String>()
val inputClickBtn = MutableLiveData<Unit?>().apply { observeForever {
errorEventStream.value =
if(inputStream.value.isIntNum()) null else "not num"
} }
// outputs
val btnEnableStream = MediatorLiveData<Boolean>().apply { value = false }.also { enable ->
enable.addSource(inputStream) { ins: String ->
enable.value = ins.isLength(3)
}
}
val errorEventStream = MediatorLiveData<String?>().apply { value = null }.also { inState ->
inState.addSource(btnEnableStream) { enable: Boolean ->
inState.value = if (enable) null else "error"
}
}
fun checkInput() {
inputClickBtn.value = null
}
fun String.isLength(len: Int) = this.length == len
fun String?.isIntNum(): Boolean {
return this != null && this.toIntOrNull()?.let { true } ?: false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment