Broadcast Receiver in kotlin

Anonymous class syntax in Kotlin is like this:

val receiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {

    }
}

I've created a BroadcastReceiver Kotlin extension, which you can copy/paste anywhere. It doesn't do much more than what is already mentioned, but it reduces some of the boilerplate. 😀

Using this extension, you should register/unregister like so:

private lateinit var myReceiver: BroadcastReceiver

override fun onStart() {
    super.onStart()
    myReceiver = registerReceiver(IntentFilter(BROADCAST_SOMETHING_HAPPENED)) { intent ->
        when (intent?.action) {
            BROADCAST_SOMETHING_HAPPENED -> handleSomethingHappened()
        }
    }
}

override fun onStop() {
    super.onStop()
    unregisterReceiver(myReceiver)
}

you can do it in the following way

Create a broadcast receiver object in your activity class

val broadCastReceiver = object : BroadcastReceiver() {
    override fun onReceive(contxt: Context?, intent: Intent?) {   
        when (intent?.action) {
           BROADCAST_DEFAULT_ALBUM_CHANGED -> handleAlbumChanged()
           BROADCAST_CHANGE_TYPE_CHANGED -> handleChangeTypeChanged()
        }
    }
}

Register broadcast receiver in onCreate() function of your activity

 LocalBroadcastManager.getInstance(this)
                    .registerReceiver(broadCastReceiver, IntentFilter(BROADCAST_DEFAULT_ALBUM_CHANGED))

unregister it in ondestroy function of your activity

LocalBroadcastManager.getInstance(this)
                .unregisterReceiver(broadCastReceiver)