Skip to content

Instantly share code, notes, and snippets.

typealias SnackFinishedListener = () -> Unit
typealias SnackActionListener = () -> Unit
/**
* Representation of [Snackbar] data that can be exposed by a view model, observed, and bound to
* the current UI
*/
sealed class SnackData
/**
/**
* Representation of [Toast] data that can be exposed by a view model, observed, and bound to
* the current UI
*/
sealed class ToastData
data class ShortToast(@StringRes val msgId:Int) : ToastData()
data class LongToast(@StringRes val msgId:Int) : ToastData()
@n8ebel
n8ebel / BaseActivity.kt
Last active January 25, 2018 03:39
Activity subscription to viewmodel ToastState
viewModel.toastPub.subscribe { toastData ->
when(toastData) {
is ShortToast -> Toast.makeText(this, toastData.msgId, Toast.LENGTH_SHORT).show()
is LongToast -> Toast.makeText(this, toastData.msgId, Toast.LENGTH_LONG).show()
}
}
@n8ebel
n8ebel / BaseViewModel.kt
Created January 25, 2018 03:42
ToastData PublishSubject on a BaseViewModel
val toastPub:PublishSubject<ToastData> = PublishSubject.create()
val snackPub:PublishSubject<SnackData> = PublishSubject.create()
@n8ebel
n8ebel / BaseActivity.kt
Last active January 25, 2018 05:09
Activity subscription to a ViewModel SnackData PublishSubject
fun bindViewModel(root:View, viewModel: BaseViewModel) {
viewModel.snackPub.subscribe { snackData ->
showSnackbar(rootView, snackData)
}
}
/**
* Maps the passed [SnackData] to the appropriate UI representation of a [Snackbar]
*/
private fun showSnackbar(root: View, data: SnackData) {
@n8ebel
n8ebel / ViewModelLifecycleData.kt
Created January 25, 2018 04:35
Definition of ViewModel lifecycle states that are handled by our BaseActivity
// Lifecycle States
sealed class ViewModelLifecycleState
object Active : ViewModelLifecycleState()
object FinishedOk : ViewModelLifecycleState()
object Cancelled : ViewModelLifecycleState()
data class FinishedWithResult(
viewModel.lifecycleStatePub.subscribe { state ->
when (state) {
is Active -> {}
is FinishedOk, Cancelled -> finish()
is FinishedWithResult -> {
setResult(state.result, state.data)
finish()
}
is StartActivity -> {
val intent = Intent(this, state.target).apply {
// Indicate the the screen should be closed
class ImageViewModel() : BaseViewModel() {
@BoundMethod
fun onExitFullscreenClicked() {
lifecycleState.set(FinishedOk)
}
}
// indicate that the screen should be finished and a result is returned
@n8ebel
n8ebel / MainActivity.kt
Created February 19, 2018 04:24
Blink Rainbow HAT LED for Android Things
class MainActivity : Activity() {
private val TAG = MainActivity::class.java.simpleName
private val blinkHandler = Handler()
private var redLED: Gpio? = null
private val blinkRunnable = object : Runnable {
override fun run() {
redLED?.also {