0

I'm going through the official React Native documentation to create native modules. I'm currently at the section to send events from native to js. I'm probably missing something but I ended up with:

package com.myapp


import android.util.Log
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule


class TestModuleKotlin(reactContext: ReactApplicationContext): ReactContextBaseJavaModule(reactContext) {
    private val reactContext: ReactContext = reactContext


    @ReactMethod fun createCalendarEvent(name: String, location: String) {
        Log.d("TestModuleKotlin", "Create Kotlin event called with name: $name and location: $location")

    }

    private fun sendEvent(reactContext: ReactContext, eventName: String, params: WritableMap?) {
        reactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
            .emit(eventName, params)
    }

    private var listenerCount = 0

    @ReactMethod
    fun addListener(eventName: String) {
        if (listenerCount == 0) {
            // Set up any upstream listeners or background tasks as necessary
        }

        listenerCount += 1
    }

    @ReactMethod
    fun removeListeners(count: Int) {
        listenerCount -= count
        if (listenerCount == 0) {
            // Remove upstream listeners, stop unnecessary background tasks
        }
    }

    val params = Arguments.createMap().apply {
        putString("eventProperty", "someValue")
    }

    @ReactMethod
    fun sendSomething() {
        sendEvent(reactContext, "EventReminder", params)
    }







    override fun getName() = "TestModuleKotlin"


}

The only thing that I added (upon some googling) was:

private val reactContext: ReactContext = reactContext

I'm not sure if that was the right way of defining/getting access to it.

Without it, in the sendSomething() method the 'reactContext' was undefined.

Adding that line that defines reactContext seems to have did the trick and it seems to work (I call the sendStuff() method from JS, which emits the message), but I was just improvising. Was it the right thing to do? I'm just starting with Kotlin and native modules. Thanks

I was expecting that I won't need to add anything additional for it to work and just follow the official tutorial. https://reactnative.dev/docs/native-modules-android?android-language=kotlin#sending-events-to-javascript

MarPor
  • 1
  • 1

0 Answers0