ubu
11/05/2019, 8:59 PMViewModel
observing flow of user accounts: Account1
, Account2
, `Account3`… Then for each of these accounts I need to load an image (represented as blob
) from some remote source. This loading may take a while, that’s why I show user accounts first without their picturse, then update UI
with the same model having now picture data. First of all, it feels a bit weird to load images inside onEach
operator. Or not? And then, maybe it’s not a good idea at all to load picture data inside a ViewModel
. What do you think?
class SelectAccountViewModel(
private val startLoadingAccounts: StartLoadingAccounts,
private val observeAccounts: ObserveAccounts,
private val loadImage: LoadImage
) : ViewModel(), SupportNavigation<Event<AppNavigation.Command>> {
val state by lazy { MutableLiveData<List<ChooseProfileView>>() }
private val accountChannel = Channel<Account>()
private val imageChannel = Channel<ImageBlob>()
init {
startObservingAccounts()
//startLoadingAccount()
viewModelScope.launch {
val accumulatedAccounts = accountChannel
.consumeAsFlow()
.onEach { account -> loadImage(account) }
.scan(emptyList<Account>()) { list, value -> list + value }
val accumulatedImages = imageChannel
.consumeAsFlow()
.scan(emptyList<ImageBlob>()) { list, value -> list + value }
accumulatedAccounts.combine(accumulatedImages) { accounts, images ->
accounts.associateWith { account ->
images.firstOrNull { it.id == account.id }
}
}.collect { result ->
state.postValue(
result.map { (account, image) ->
ChooseProfileView.ProfileView(
id = account.id,
name = account.name,
image = image?.blob
)
}
)
}
}
}
}
And then, these other questions arise: is it okay to use channels as shown above? Could one be more concise with coroutines?zak.taccardi
11/05/2019, 9:00 PMubu
11/06/2019, 1:12 PM