UIKit Android v3
UIKit Android
UIKit
Android
Version 3
Home
/
UIKit
/
Android
/
Customization

Add new APIs to the fragment

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.
public class CustomChannelViewModel extends ChannelViewModel {

    // Add a new API.

    public void leaveChannel(@Nullable OnCompleteHandler handler) {
        getChannel().leave(e -> {
            if (handler != null) handler.onComplete(e);
        });
    }
}
  1. Create CustomChannelViewModel through ViewModelFactory.
private static class CustomViewModelFactory extends ViewModelFactory {
    private final String channelUrl;
    private final MessageListParams params;

    public CustomViewModelFactory(@NonNull String channelUrl, @Nullable MessageListParams params) {
        this.channelUrl = channelUrl;
        this.params = params;
    }

    @SuppressWarnings("unchecked")
    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        // Return the customized `ViewModel`.
        if (modelClass.isAssignableFrom(CustomChannelViewModel.class)) {
            return (T) new CustomChannelViewModel(channelUrl, params);
        } else {
            return super.create(modelClass);
        }
    }
}
  1. Create a custom ViewModel by overriding the onCreateViewModel() method of the custom fragment.
public class CustomChannelFragment extends ChannelFragment {
    @NonNull
    @Override
    protected ChannelViewModel onCreateViewModel() {
        final String channelUrl = getChannelUrl();
        return new ViewModelProvider(this, new CustomViewModelFactory(channelUrl, new MessageListParams())).get(channelUrl, CustomChannelViewModel.class);
    }

    // Add a new API that leaves the channel to the right button of the `ChannelHeaderComponent` as an example.
    @Override
    protected void onBindChannelHeaderComponent(ChannelHeaderComponent header, ChannelViewModel viewModel, GroupChannel channel) {
        CustomChannelViewModel customChannelViewModel;
        if (viewModel instanceof CustomChannelViewModel) {
            customChannelViewModel = (CustomChannelViewModel) viewModel;

            // Try and call the new API.
            header.setOnRightButtonClickListener(v -> {
                customChannelViewModel.leaveChannel(e -> {
                    if (e == null) {
                        shouldActivityFinish();
                    }
                });
            });
        }
    }
}

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