Channels View Model

Last Edit: Nov 27 2020

ChannelsViewModel is responsible for updating ChannelsView based on data received from StreamChatAndroidOffline library. It queries the channels during initialization and updates its state every time channels are updated.

The view model exposes LiveData object called state, which can be one of following:

  • LoadingNextPage

  • Loading

  • Result

  • EndPageReached

  • NoChannelsAvailable

  • NavigateToLoginScreen

You can inform the view model about new events using onEvent method. Currently, ChannelsViewModel supports the following events:

  • ReachedEndOfList

  • LogoutClicked

Creating Channels View Model

ChannelsViewModel can be instantiated using ChannelsViewModelFactory:


FilterObject filter = Filters.and(
        Filters.eq("type", "messaging"),
        Filters.in("members", singletonList(user.getId()))
);
QuerySort sort = ChannelsViewModel.DEFAULT_SORT;
int limit = 30;

ChannelsViewModelFactory factory = new ChannelsViewModelFactory(filter, sort, limit);
ChannelsViewModel viewModel = new ViewModelProvider(this, factory)
        .get(ChannelsViewModelImpl.class);
                    

private val filter: FilterObject = Filters.and(
    Filters.eq("type", "messaging"),
    Filters.`in`("members", listOf(ChatDomain.instance().currentUser.id))
)
private val sort: QuerySort = ChannelsViewModel.DEFAULT_SORT
private val limit: Int = 30

private val viewModel: ChannelsViewModelImpl by viewModels {
    ChannelsViewModelFactory(filter, sort, limit)
}
                    

Binding with ChannelsView

ChannelsViewModel can be bound with ChannelsView using ChannelsViewModelBinding:


ChannelsViewModelBinding.bind(viewModel, channelsView, lifecycle);
                    

viewModel.bindView(channelsView, viewLifecycleOwner)
                    

The bind call connects the view model with the view and from that point, different channels view states (Result, Loading, NoChannelsAvailable) will be handled automatically. Moreover, it sets view's OnEndReachedListener which is responsible for loading more channels when user reaches end of the list.