Created
November 17, 2018 12:26
-
-
Save marenovakovic/bf88b8f9ece93388e0ba20d298adc440 to your computer and use it in GitHub Desktop.
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
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