Simple and light-weight event dispatcher for Kotlin

Overview

KDispatcher is a Kotlin EventDispatcher

Kotlin 1.4.31 Download Codacy Badge Awesome Kotlin Badge

This is light-weight event dispatcher based on KOTLIN

  • priority: Int? = null to subscribe function for sorting
  • Inline function Included

You can subscribe on event by calling:

val EVENT_CALL_ONE = "simple_event_name"
val eventListener = ::eventHandler
val priority = 1
KDispatcher.subscribe(EVENT_CALL_ONE, eventListener, priority)

where:

  • EVENT_CALL_ONE - simple event type
  • eventListener - function listener for event
  • priority - the priority to sort calling functions
/**
* notif:Notification<T:Any> - event holder object that store
* data:T? = null - can be any type of data
* eventName:String? = null - current event type
* cause u may have more then one EVENT_TYPE for current event listener
*/
fun eventHandler(notif:Notification<Any>){
  when(notif.eventName){
      EVENT_CALL_ONE -> println("FIRST EVENT")
  }
}

Of course u can simpe call the event for all listeners by

val test:MyTestClass = MyTestClass()
KDispatcher.call(EVENT_CALL_ONE, test)

Don't forget to unsubscribe your listeners when u dont need it anymore.

KDispatcher.unsubscribe(EVENT_CALL_ONE, eventListener)

Sinse version 0.1.2 you can use extension and inline functions of KDispatcher. All you need to do is implement IKDispatcher interface. Also you can use single lambda functions like (Notification<T:Any>) -> Unit as event handlers

class MainActivity : AppCompatActivity(), IKDispatcher {

    private val eventListenerOne = this::eventOneHandler
    //...
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        scopeOperation()
    }
    
    private fun scopeOperation() {
        // subscribe event to this handlers
        subscribe(EVENT_CALL_ONE, eventListenerOne, 3)
        subscribe(EVENT_CALL_ONE, ::eventListenerTwo, 1)
        subscribe(EVENT_CALL_ONE, MyClass::eventListenerFour, 2)
        // call event
        call(EVENT_CALL_ONE, "FIRST CALL FROM KDISPATCHER")
        
        /**
         * But you can simple use inner lambda function to handler notification.
         * So as u hasn't a reference to ISubscriber handler function, when you call
         * `usubscribe(String)` you will delete all references ISubscriber-listener
         */
        val eventName = "LAMBDA_EVENT"
        subscribe<String>(eventName) { notification ->
            println("LAMBDA_EVENT HAS FIRED with event name ${notification.eventName} and data ${notification.data}")
            unsubscribe(notification.eventName)
        }
        
        call(eventName, "FIRST CALL CUSTOM LABDA EVENT")
        
        /**
        * Since version 0.1.7 you can subscribe by scope of events by a single callback
        */
        subscribeList<Any>(listOf("notif_one", "notif_two")) {
            when(it.eventName) {
                "notif_one" -> Toast.makeText(this, "This is notif_one", Toast.LENGTH_SHORT).show()
                "notif_two" -> Toast.makeText(this, "This is notif_two", Toast.LENGTH_SHORT).show()
            }
        }

        call("notif_one")
        call("notif_two")
    }
    
    fun eventOneHandler(notification:Notification<Any>) {
       println("eventOneHandler MY TEST IS COMING event = ${notification.eventName} AND data = ${notification.data}")
    }

}

Gradle:

implementation 'com.rasalexman.kdispatcher:kdispatcher:x.y.z'

Maven:

<dependency>
  <groupId>com.rasalexman.kdispatcher</groupId>
  <artifactId>kdispatcher</artifactId>
  <version>x.y.z</version>
  <type>pom</type>
</dependency>
  • ThreadSafe
  • Simple
  • Usefull

License


MIT License

Copyright (c) 2021 Alexandr Minkin ([email protected])

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You might also like...
🎲 A powerful and simple-to-use guilded wrapper made in Kotlin.

🎲 deck [WIP] Deck is a powerful yet simple-to-use guilded wrapper made entirely in Kotlin with support to multiplatform. Implementating In case you'r

A simple, classic Kotlin MVI implementation based on coroutines with Android support, clean DSL and easy to understand logic

A simple, classic Kotlin MVI implementation based on coroutines with Android support, clean DSL and easy to understand logic

This repository contains the article describing my attempt to implement a simple state reducer based on Kotlin Flow and an example app that uses it.
This repository contains the article describing my attempt to implement a simple state reducer based on Kotlin Flow and an example app that uses it.

This repository contains the article describing my attempt to implement a simple state reducer based on Kotlin Flow and an example app that uses it.

A simple and easy adapter for RecyclerView. You don't have to make adapters and view holders anymore. Slush will help you.
A simple and easy adapter for RecyclerView. You don't have to make adapters and view holders anymore. Slush will help you.

ν•œκ΅­μ–΄ No more boilerplate adapters and view holders. Slush will make using RecyclerView easy and fast. The goal of this project is to make RecyclerView,

A simple e-market application that allows users to view the store details and products, add products to the basket, and place an order.
A simple e-market application that allows users to view the store details and products, add products to the basket, and place an order.

E-Market Application Features : Store details & products screen Fetch the store detail from an endpoint and display this upper part of the screen. Fet

Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Practical Kotlin Multiplatform on the Web λ³Έ μ €μž₯μ†ŒλŠ” μ½”ν‹€λ¦° λ©€ν‹°ν”Œλž«νΌ 기반 μ›Ή ν”„λ‘œκ·Έλž˜λ° μ›Œν¬μˆ(κ°•μ’Œ)을 μœ„ν•΄ μž‘μ„±λœ ν…œν”Œλ¦Ώ ν”„λ‘œμ νŠΈκ°€ μžˆλŠ” κ³³μž…λ‹ˆλ‹€. μ›Œν¬μˆ κ³Όμ •μ—μ„œ μ½”ν‹€λ¦° λ©€ν‹°ν”Œλž«νΌμ„ 기반으둜 ν”„λ‘ νŠΈμ—”λ“œ(front-end)λŠ” Ko

Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Building a Full Stack Web App with Kotlin Multiplatform λ³Έ μ €μž₯μ†ŒλŠ” INFCON 2022μ—μ„œ μ½”ν‹€λ¦° λ©€ν‹°ν”Œλž«νΌ 기반 μ›Ή ν”„λ‘œκ·Έλž˜λ° ν•Έμ¦ˆμ˜¨λž©μ„ μœ„ν•΄ μž‘μ„±λœ ν…œν”Œλ¦Ώ ν”„λ‘œμ νŠΈκ°€ μžˆλŠ” κ³³μž…λ‹ˆλ‹€. ν•Έμ¦ˆμ˜¨ κ³Όμ •μ—μ„œ μ½”ν‹€λ¦° λ©€ν‹°ν”Œλž«νΌμ„

A simple Kotlin wrapper around Anvil.

AnvilKotlin A simple Kotlin wrapper around Anvil. The only purpose of this library is to provide type safety to Anvil through Kotlin. Nothing more, no

A simple way to handle remote image in Kotlin.
A simple way to handle remote image in Kotlin.

Parrot A kotlin extension to load easily remote images in your ImageView. Install Add to gradle in allprojects maven { url 'https://jitpack.io' } the

Comments
  • If a subscribe callback subscribes to the same event, ConcurrentModificationException is thrown

    If a subscribe callback subscribes to the same event, ConcurrentModificationException is thrown

    Since the list of callbacks is being iterated during the subscribe() callback, a new subscribe inside the call hierarchy of the callback calls add() to the same list. Therefore a ConcurrentModificationException is thrown.

    opened by etanhatch 2
  • Suggestions

    Suggestions

    1. Have the priority optional
    2. Have function that will auto-register and un-register, using Lifecycle library:

    https://developer.android.com/topic/libraries/architecture/lifecycle

    opened by AndroidDeveloperLB 2
  • 1.7 - multiple subscribers

    1.7 - multiple subscribers

    When using the subscribeList approach introduced in 1.7, the first subscribeList does fire correctly when doing a call (publish). But the second subscribeList subscriber will not receive the events.

    This error is only happening when using the subscribeList feature. It is not a problem when doing a single subscribe, multiple times on the same topic.

    opened by nanolink 1
Releases(1.1.92)
  • 1.1.92(May 8, 2021)

  • 1.1.91(May 8, 2021)

  • 1.1.9(Mar 24, 2021)

  • 1.1.7(Sep 17, 2020)

  • 1.1.6(Jun 27, 2020)

    Fix bug with ConcurrentModificationException when subscribing to listener from handler function Kotlin version 1.3.72 kdispatcher module fully migrated to kotlin dsl plugin

    Source code(tar.gz)
    Source code(zip)
  • 1.1.3(Oct 15, 2019)

    Added new call function with infix callWith Kotlin version 1.3.50 refactor of priority parameter in

    • subscribe(notif: String, priority: Int? = null, noinline sub: Subscriber<T>)
    • subscribeList(notifs: List<String>, priority: Int? = null, noinline sub: Subscriber<T>)

    extend documentation

    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(Jul 14, 2019)

  • 1.0.0(Dec 24, 2018)

  • 0.1.8(Aug 23, 2018)

    • min sdk 19
    • added IKDispatcher.subscribe(notif: String, noinline sub: Subscriber<T>) without priority
    • changed IKDispatcher.subscribe(notif: String, noinline sub: Subscriber<T>, priority: Int? = null) params sorting
    • changed HashMaps to ArrayMaps for better memory improvement
    • added check hasSubscribers in IKDispatcher.subscribeList extension method
    Source code(tar.gz)
    Source code(zip)
  • 0.1.7(Aug 6, 2018)

  • 0.1.6(Jul 22, 2018)

  • 0.1.5(Jul 20, 2018)

    change callback handler params count and type. Now it's a Notification object that holds your data in var and clear after executing the handler.

    • fun IKDispatcher.subscribe now inline with reified generic type for Notification data
    • update a simple app example
    Source code(tar.gz)
    Source code(zip)
  • untagged-c991bf85b8af729eac1a(Jun 26, 2018)

  • 0.1.1(Mar 22, 2018)

Owner
Alexandr Minkin
Lead Software Developer - Kotlin - Swift - Java - C#
Alexandr Minkin
A light lib that helps and centralize logs in your application.

BadgeLog (Kotlin version) For the iOS swift version, see this page BadgeLog is an Android Kotlin library that helps you manage logs within your applic

Daniele 1 Feb 8, 2022
Clean MVVM with eliminating the usage of context from view models by introducing hilt for DI and sealed classes for displaying Errors in views using shared flows (one time event), and Stateflow for data

Clean ViewModel with Sealed Classes Following are the purposes of this repo Showing how you can remove the need of context in ViewModels. I. By using

Kashif Mehmood 22 Oct 26, 2022
RoomJetpackCompose is an app written in Kotlin and shows a simple solution to perform CRUD operations in the Room database using Kotlin Flow in clean architecture.

RoomJetpackCompose is an app written in Kotlin and shows a simple solution to perform CRUD operations in the Room database using Kotlin Flow in clean architecture.

Alex 27 Jan 1, 2023
Nice and simple DSL for Espresso in Kotlin

Kakao Nice and simple DSL for Espresso in Kotlin Introduction At Agoda, we have more than 1000 automated tests to ensure our application's quality and

Agoda Company Pte Ltd. 1.1k Nov 22, 2022
Dead simple EventBus for Android made with Kotlin and RxJava 2

KBus Super lightweight (13 LOC) and minimalistic (post(), subscribe(), unsubscribe()) EventBus written with idiomatic Kotlin and RxJava 2 KBus in 3 st

Adriel CafΓ© 46 Dec 6, 2022
🚟 Lightweight, and simple scheduling library made for Kotlin (JVM)

Haru ?? Lightweight, and simple scheduling library made for Kotlin (JVM) Why did you build this? I built this library as a personal usage library to h

Noel 13 Dec 16, 2022
Simple Kotlin Multiplatform PrayerTimes App for iOS and Android

Kotlin Multiplatform ___ _______ ___ / _ \_______ ___ _____ ___/_ __(_)_ _ ___ ___ / _ | __

Ahmed El-Helw 26 Nov 9, 2022
A lightweight and simple Kotlin library for deep link handling on Android πŸ”—.

A lightweight and simple Kotlin library for deep link handling on Android ??.

Jeziel Lago 101 Aug 14, 2022
⏰ A powerful and simple-to-use guilded wrapper made in Kotlin.

⏰ guilded-kt [WIP] A powerful yet simple-to-use guilded wrapper made entirely in Kotlin with supporting multiplatform. Take a look at an example of th

Gabriel 13 Jul 30, 2022