UIKit Android v3
UIKit Android
UIKit
Android
Home
/
UIKit
/
Android
This is the new Docs for UIKit v3 for Android. To see the previous Docs, click here.

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) {
        channel.leave(e -> {
            if (handler != null) handler.onComplete(e);
        });
    }
}
  1. Create CustomChannelViewModel through ViewModelFactory.
public class ViewModelFactory extends ViewModelProvider.NewInstanceFactory {

    private final Object[] params;

    public ViewModelFactory(@NonNull Object... params) {
        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 ViewModelFactory(channelUrl)).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.