Simple event library to communicate between Activity/Fragment and ViewModel

Overview

Setup

dependencies {
    implementation "com.github.skgmn:viewmodelevent:1.1.0"
}

If you don't know how to access to GitHub Packges, please refer to this.

Usage

Basic Usage of Event

class MyViewModel : ViewModel() {
    val myEvent = publicEvent<MyEvent>()
    
    fun hello() {
        myEvent.post(MyEvent())
    }
}

class MyActivity : AppCompatActivity() {
    private val viewModel: MyViewModel by viewModels()
    
    fun onCreate(savedInstanceState: Bundle?) {
        handle(viewModel.myEvent) { doSomeWorkWith(it) }
    }
}

If you want to inhibit other than MyViewModel from posting events, then create private Delivery and post events through it.

class MyViewModel : ViewModel() {
    private val myEventDelivery = delivery<MyEvent>()
    val myEvent = event(myEventDelivery)
    
    private val yourEventDelivery = delivery<YourEvent>()
    val yourEvent = event(yourEventDelivery)
    
    fun hello() {
        myEventDelivery.post(MyEvent())
        yourEventDelivery.post(YourEvent())
    }
}

class MyActivity : AppCompatActivity() {
    private val viewModel: MyViewModel by viewModels()
    
    fun onCreate(savedInstanceState: Bundle?) {
        handle(viewModel.myEvent) { doSomeWorkWith(it) }
        handle(viewModel.yourEvent) { doOtherThingsWith(it) }
    }
}

If you are free to make your ViewModel inherit other classes, make it extend com.github.skgmn.viewmodelevent.ViewModel rather than androidx.lifecycle.ViewModel. It becomes even easier.

class MyViewModel : com.github.skgmn.viewmodelevent.ViewModel() {
    val myEvent = event<MyEvent>()
    
    fun hello() {
        // this post() is invisible to the outside of MyViewModel
        myEvent.post(MyEvent())
    }
}

Event Lifecycle

Event delivery occurs only between onStart() and onStop()

The lambda function passed to handle() is only invoked when its Activity or Fragment is between onStart() and onStop().

Events are buffered after onStop()

Events posted after onStop() are buffered until the Activity or Fragment retarts. Only the latest item is buffered if DeliveryMode.LATEST is passed to handle()(this is the default behavior). Otherwise, all items are buffered if DeliveryMode.ALL is passed to handle().

Events live across Activity recreation

Events posted while Activity recreation can be delivered after it is recreated.

Multiple handling

An Activity or Fragment can handle multiple events, but cannot handle the same event multiple times. Only the latest handler will work then. It is OK that several Activities or Fragments handle the same event at the same time. It can be useful when some ViewModels are shared by many Activities or Fragments.

Survey

A Survey is a concept similar to Event, but it can reply to its sender.

class MyViewModel : ViewModel() {
    val mySurvey = survey<MyQuestion>()
    
    fun hello() {
        viewModelScope.launch {
            mySurvey.ask(MyQuestion()).collect { myAnswer ->
                doSomethingWith(myAnswer)
            }
        }
    }
}

class MyActivity : AppCompatActivity() {
    private val viewModel: MyViewModel by viewModels()

    fun onCreate(savedInstanceState: Bundle?) {
        answer(viewModel.mySurvey) { question ->
            MyAnswerTo(question)
        }
    }
}
Event Survey
publicEvent() publicSurvey()
delivery() poll()
event() survey()
post() ask()
handle() answer()

Unlike Event, Survey use coroutine. Survey.ask() returns Flow, and Survey.answer() accepts suspend lambda function. Survey also has same lifecycle as Event.

License

MIT License

Copyright (c) 2021 skgmn

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...
Event-driven application uses React, reactive Spring Boot WebFlux, R2DBC, MySQL and Liquibase

Product delivery Event-driven application uses React, reactive Spring Boot WebFlux, R2DBC, MySQL and Liquibase Status: IN PROGRESS if [[ "" != `docker

This repository contains event driven redis app uses redis streams

Spring Boot Redis Streams This repository contains event driven redis app uses redis streams Run redis in docker docker run --rm --name redis -itp6379

Micorservice with event sourcing sample kotlin

micorservice-with-event-sourcing-sample-kotlin Event Sourcing Exercises. Maybe it should work. Project eventsourcing Event Sourcing by Jpa or Cosmos D

Explain - An application does not have a dialog box to confirm an event

Explain An application does not have a dialog box to confirm an event. This library is designed in a way that makes it easy for the developer to use a

Event Sourcing with Kotlin
Event Sourcing with Kotlin

This is a sample app to demonstrate the power of using EventSourced models and the ease with which these can be modelled using Kotlin.

This library handles conversion between Request Params and JPA Specification.

Spring Jpa Magic Filter This library handles conversion between spring rest Request Params and JPA Specification. It can be considered a simpler alter

This project demonstrates the usage of Android Activity Recognition Transition API
This project demonstrates the usage of Android Activity Recognition Transition API

User Activity Detection This project demonstrates the usage of Android Activity Recognition Transition API. Detect when users start or end an activity

Open currenty activity in Android Studio

Open Current Activity Android Studio / IntelliJ Plugin A little plugin for Android development (Android Studio or IntelliJ). Adds an action under Navi

Library to generalize functionality between several projects
Library to generalize functionality between several projects

libreforge libreforge is a library to generalize functionality between several projects, notably EcoArmor, EcoWeapons, and Reforges. Get from JitPack:

Releases(v1.1.0)
Owner
null
Viewmodel-lifecycle - ViewModel Lifecycle allows you to track and observe Jetpack ViewModel's lifecycle changes

ViewModel Lifecycle ?? ViewModel Lifecycle allows you to track and observe Jetpa

Jaewoong Eum 36 Feb 6, 2022
Kotlin library to communicate with LinuxCNC using JNI.

Kotlin LinuxCNC Kotlin library to communicate with LinuxCNC using JNI. Setup Assuming you have linuxcnc installed Env variables You need to set some e

Rachieru Dragos 1 May 18, 2022
Reia is the Redis Pubsub client that Manase uses to communicate with other modules or nodes.

from Mana Reia is a simple wrapper around Lettuce to enable easy usage of its Redis Pubsub client. This library is only intended to be used for sendin

Mana 1 Apr 29, 2022
This prototype app provides a list of events to be held under an organization (school, college, club, etc.) and the users can manually set event reminders at their scheduled time so that they do not miss an event.

E-CELL NITS Sample App This prototype app provides a list of events to be held under E-Cell NIT Silchar (for example, Srijan 2.0) and the users can ma

Ritam Nath 1 Nov 7, 2021
In this single activity app. i was trying to practice on ViewModel and Livedata

CalwithViewModel In this single activity app. i was trying to practice on ViewModel and Livedata Min Api Level : 19 Setup Requirements Android device

Tech_G 1 Feb 16, 2022
A webapp which generates a simple Discord profile banner image in real-time which shows user's status and activity.

DiscordProfileBanner This tool generates a Discord profile banner image in realtime. I wrote it for use in my AniList profile. An example in action: H

Quanta 11 Oct 17, 2022
A lightweight library for requesting and consuming Activity Results using coroutines.

SuspendActivityResult A lightweight library for requesting and consuming Activity Results using coroutines, it's usage is as simple as: val uri = Acti

Hicham Boushaba 71 Dec 23, 2022
Native-Blur: a C++/Kotlin library for blur bitmaps and activity, mobile-ready, android compatible

Native-Blur The Native-Blur is a C++/Kotlin libraray for blur bitmaps and activity, mobile-ready, android compatible, powered by Java Native Interface

Abolfazl Abbasi 26 Dec 13, 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
Event State Processor Generator plugin is compatible with IntelliJ and Android Studio.

Event State Processor Generator plugin is compatible with IntelliJ and Android Studio. It provides source code generation for the EventStateProcessor Library to increase code productivity in Flutter apps development.

Extreme Vietnam Public 2 Dec 7, 2021