Skip to content

Instantly share code, notes, and snippets.

@mrsasha
Last active February 18, 2020 16:25
Show Gist options
  • Save mrsasha/3e0f61a2a7c962c4216d5e06e425020e to your computer and use it in GitHub Desktop.
Save mrsasha/3e0f61a2a7c962c4216d5e06e425020e to your computer and use it in GitHub Desktop.
viewmodels with channels
private fun observeViewModel() {
mainViewModel.observe(lifecycleScope) {
when (it) {
MainScreenState.InProgress -> showProgress()
}
}
}
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.launch
abstract class BaseViewModel<S, E> : ViewModel() {
protected open val channel: Channel<S> = Channel()
fun observe(scope: CoroutineScope, observer: (S) -> Unit) {
scope.launch {
channel.consumeEach { it?.let(observer::invoke) }
}
}
fun post(state: S) {
channel.offer(state)
}
abstract fun send(event: E)
}
dependencies {
implementation Libs.lifecycle_extensions
implementation Libs.lifecycle_runtime
implementation Libs.lifecycle_viewmodel
}
object Versions {
const val lifecycle_version = "2.2.0-rc03"
}
object Libs {
const val lifecycle_extensions = "androidx.lifecycle:lifecycle-extensions:${Versions.lifecycle_version}"
const val lifecycle_runtime = "androidx.lifecycle:lifecycle-runtime-ktx:${Versions.lifecycle_version}"
const val lifecycle_viewmodel = "androidx.lifecycle:lifecycle-viewmodel-ktx:${Versions.lifecycle_version}"
}
sealed class MainScreenEvent {
object Load : MainScreenEvent()
}
sealed class MainScreenState {
object InProgress : MainScreenState()
}
class MainViewModel() : BaseViewModel<MainScreenState, MainScreenEvent>() {
override fun send(event: MainScreenEvent) {
when (event) {
MainScreenEvent.Load -> doSomething()
}
}
private fun doSomething() {
post(MainScreenState.InProgress)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment