Chat UIKit Android v3
Chat UIKit Android
Chat UIKit
Android
Version 3

Add new APIs to the fragment

Copy link

The ViewModel updates and manages APIs used in the fragment. It communicates with Sendbird Chat SDK to receive necessary data. If you wish to customize these data and implement new APIs, you can do so through the ViewModel.

Note: The ViewModel of ChannelFragment is used as an example in the codes below to show how to customize it but you can replace it with any other ViewModel in UIKit.

  1. You can add or override new methods by inheriting ChannelViewModel.
KotlinJava
class CustomChannelViewModel(
    channelUrl: String
) : ChannelViewModel(channelUrl, null) {

    // Add a new API.

    fun leaveChannel(handler: OnCompleteHandler?) {
        channel?.leave { e -> handler?.onComplete(e) }
    }
}
  1. Create CustomChannelViewModel through ViewModelFactory.
KotlinJava
class CustomViewModelFactory(
    private val channelUrl: String
) : ViewModelFactory() {
    
    @Suppress("unchecked_cast")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        // Return the customized `ViewModel`.
        return if (modelClass.isAssignableFrom(CustomChannelViewModel::class.java)) {
            CustomChannelViewModel(channelUrl) as T
        } else {
            super.create(modelClass)
        }
    }
}
  1. Create a custom ViewModel by overriding the onCreateViewModel() method of the custom fragment.
KotlinJava
class CustomChannelFragment : ChannelFragment() {
    override fun onCreateViewModel(): ChannelViewModel {
        return ViewModelProvider(
            this,
            CustomViewModelFactory(channelUrl)
        ).get(
            channelUrl,
            CustomChannelViewModel::class.java
        )
    }

    // Add a new API that leaves the channel to the right button of the `ChannelHeaderComponent` as an example.
    override fun onBindChannelHeaderComponent(
        header: ChannelHeaderComponent,
        viewModel: ChannelViewModel,
        channel: GroupChannel?
    ) {
        if (viewModel is CustomChannelViewModel) {
            // Try and call the new API.
            header.setOnRightButtonClickListener {
                viewModel.leaveChannel { e: SendbirdException? ->
                    if (e == null) shouldActivityFinish()
                }
            }
        }
    }
}

You can use the newly customized ViewModel by calling the getViewModel() method of the custom fragment.