Manual injection

If you use your own DI framework or if you just want to have control on the instance of the Nabla SDK used by UI components, you can provide your own instance.

Get your own Nabla instances

Instead of relying on the NablaClient.getInstance() and NablaMessagingClient.getInstance() singleton, you can create your own instance and use it. Here's an exemple using Hilt:

@Module
@InstallIn(SingletonComponent::class)
object NablaModule {
  @Provides
  @Singleton
  fun provideNablaCoreClient(
    @ApplicationContext context: Context,
  ): NablaClient = NablaClient.initialize(
    name = "MyOwnNablaInstance",
    configuration = Configuration(
      context = context,
      publicApiKey = "MY_API_KEY"
    )
  )
    
  @Provides
  @Singleton
  fun provideNablaMessagingClient(
    nablaClient: NablaClient,
  ): NablaMessagingClient = NablaMessagingClient.initialize(
      nablaClient = nablaClient,
  )
}

📘

Make sure not to forget to also authenticate your user before using the rest of the APIs. See Setup for details about how to do it.

UI Component: Conversations list

You can pass your own NablaMessagingClient instance to the ConversationListViewModelFactory and then use that factory with the ConversationListViewModel:

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    @Inject
    lateinit var nablaMessagingClient: NablaMessagingClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Pass your nabla instance to the factory
        val viewModel: ConversationListViewModel by viewModels {
            ConversationListViewModelFactory(
                owner = this,
                messagingClient = nablaMessagingClient,
            )
        }

        // Step 2 - Connect the View to the ViewModel
        // If you're using a Fragment, the lifecycleOwner is "viewLifecycleOwner"
        binding.conversationListView.bindViewModel(
            viewModel,
            onConversationClicked = { id: ConversationId ->
                // TODO handle click on a conversation
            },
        )
    }
}

UI Component: Conversation screen

To provide your own instance to the ConversationFragment, you need to extend it and override the nablaMessaging property.

class MyConversationFragment : ConversationFragment() {

  @Inject override lateinit var messagingClient: NablaMessagingClient

}

Then you can instantiate it using the newInstance convenience method:

val myConversationFragment = ConversationFragment.newInstance(conversationId) {
  setFragment(MyConversationFragment())
}

Did this page help you?