Skip to content

Instantly share code, notes, and snippets.

@marenovakovic
Created November 17, 2018 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marenovakovic/bf88b8f9ece93388e0ba20d298adc440 to your computer and use it in GitHub Desktop.
Save marenovakovic/bf88b8f9ece93388e0ba20d298adc440 to your computer and use it in GitHub Desktop.
package com.marko.presentation.coins
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.marko.domain.entities.CoinEntity
import com.marko.domain.result.Result
import com.marko.domain.usecase.GetCoins
import com.marko.domain.usecase.invoke
import com.marko.presentation.base.BaseViewModel
import com.marko.presentation.entities.Coin
import com.marko.presentation.mappers.toPresentation
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.launch
class CoinsViewModel(
private val getCoins: GetCoins
) : BaseViewModel() {
private val _loading = MutableLiveData<Boolean>()
val loading: LiveData<Boolean>
get() = _loading
private val _coins = MutableLiveData<List<Coin>>()
val coins: LiveData<List<Coin>>
get() = _coins
private val _error = MutableLiveData<Exception>()
val error: LiveData<Exception>
get() = _error
fun fetch() {
launch {
getCoins { launch { dispatch(it) } }
}
}
private suspend fun dispatch(channel: ReceiveChannel<Result<List<CoinEntity>>>) {
channel.consumeEach {
when (it) {
is Result.Loading -> _loading::postValue
is Result.Success -> _coins.postValue(it.data.toPresentation())
is Result.Error -> _error::postValue
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment