Last active
September 14, 2016 13:43
-
-
Save passsy/25ade32b70f4dbcc7303586e19d1c1cd to your computer and use it in GitHub Desktop.
VPVM Example of a ViewModel which can be used inside a ThirtyInch TiPresenter. This is built with Kotlin and Rx. While you may not use those technologies in your app you get the idea
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
private class ViewModel { | |
private var changing = PublishSubject.create<Unit>() | |
fun observe(): Observable<ViewModel> { | |
return Observable.just(this).mergeWith(changing.map { this }) | |
} | |
var results: List<SearchResult> by onChangeNotifySubject(emptyList(), changing, | |
{ p, o, newValue -> if (newValue.isEmpty()) selectedResult = null }) | |
var selectedResult: SearchResult? by onChangeNotifySubject(null, changing) | |
var dialog: ErrorDialog? by onChangeNotifySubject(null, changing) | |
var showGeoSearchError: Boolean = false | |
fun bindToView(view: GeoSearchView) { | |
view.showSearchResults(results, selectedResult) | |
dialog?.let { | |
view.showErrorDialog(it.id, it.error) | |
} ?: run { | |
view.closeErrorDialog() | |
} | |
view.showGeoSearchError(showGeoSearchError) | |
} | |
} | |
/** | |
* Returns a property delegate for a read/write property that emits `null` to the subject. | |
* @param initialValue the initial value of the property. | |
* @param subject `onNext(next)` will be called after the change | |
* @param action invoked before the subject will be triggered | |
*/ | |
fun <T> onChangeNotifySubject( | |
initialValue: T, | |
subject: Subject<Unit, Unit>, | |
action: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit = { p, o, n -> }): ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) { | |
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) { | |
action(property, oldValue, newValue) | |
// Yes, I haven't updated to RxJava 2 | |
subject.onNext(null) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment