Created
November 11, 2018 15:38
-
-
Save ShinichiroFunatsu/ea08b05573420e4925405852947f2b5f to your computer and use it in GitHub Desktop.
Reactive Sample with Live Data
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
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