I have a `ViewModel` observing flow of user accoun...
# coroutines
u
I have a
ViewModel
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?
Copy code
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?
z
channels are how you communicate between different coroutines, so I would say yes
u
@zak.taccardi, are using channels and flows in a somewhat similar way?