Realize EventBus with LiveData

Related tags

Kotlin LiveDataBus
Overview

LiveDataBus

增強UnPeek-LiveData,將其包裝成觀察者模式的事件總線

Getting started

  1. Add it in your root build.gradle at the end of repositories:
     allprojects {
       repositories {
         // ...
         maven { url 'https://jitpack.io' }
       }
     }
  2. Add the dependency
    dependencies {
             implementation 'com.github.JaredDoge:LiveDataBus:{latest_version}'
      }

Usage

observe

LiveDataBus.get<String>(key).observe(lifecycleOwner){
            print(it)
}

當你的lifecycleOwner使用fragment時,可以調用擴充方法toViewLife()將其轉為viewLifecycleOwner

setValue

LiveDataBus.get<String>(key).setValue(msg)

SingleLiveData

當然,你可以單獨使用SingleLiveData,以確保訊息來源是可靠的。

例如在viewModel中:

class MainViewModel : ViewModel() {

    val showToast: SingleLiveData<String> = SingleLiveData<String>()
    
    fun show(){
        showToast.setValue("testMsg")
    }
}

Activity

mainViewModel.showToast.observe(this){
    //確保訊息來源是來自MainViewModel的showToast
    Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
}  

Dynamic Proxy

除了使用.get(key)取得總線外,還可以使用.of()的方式,避免key打錯的問題。 首先先建立一個interface

interface

interface SampleEvent {

    //Int為總線的資料型態      
    fun message(): SingleLiveData<Int>
    
    //可以建立多個總線
    //fun message2(): SingleLiveData<String>
    //fun message3(): StringLvieData<MyJavaBean>
    //....
}

因為使用動態代理的關係,所以必須是interface

observe

LiveDataBus.of<SampleEvent>().message().observe(this){
  //it is Int
}

setValue

LiveDataBus.of<SampleEvent>().message().setValue(123)
You might also like...
ViewModel e LiveData - Android Studio - Kotlin

Unscramble App Starter code for Android Basics codelab - Store the data in a ViewModel Unscramble is a single player game app that displays scrambled

A minimal notes application in Jetpack Compose with MVVM architecture. Built with components like DataStore, Coroutines, ViewModel, LiveData, Room, Navigation-Compose, Coil, koin etc.
A minimal notes application in Jetpack Compose with MVVM architecture. Built with components like DataStore, Coroutines, ViewModel, LiveData, Room, Navigation-Compose, Coil, koin etc.

Paper - A Minimal Notes App A minimal notes application in Jetpack Compose with MVVM architecture. Built with components like DataStore, Coroutines, V

Android Clean Architechture with MVVM, LiveData, Coroutine, Dagger Hilt, Room, DataStore
Android Clean Architechture with MVVM, LiveData, Coroutine, Dagger Hilt, Room, DataStore

MovKu An application that displays a list of popular movies and detail Concepts Tech Stack Kotlin -A modern programming language that makes developers

[Android-Kotlin] MVVM, ViewModel, LiveData, Observer, DataBinding, Repository, Retrofit, Dagger example

SimpleMvvmDaggerKotlin [Android-Kotlin] MVVM, ViewModel, LiveData, Observer, DataBinding, Repository, Retrofit, Dagger example [Image1 : User informat

eventbus-intellij-plugin 3.8 0.0 L1 Java Plugin to navigate between events posted by EventBus.
eventbus-intellij-plugin 3.8 0.0 L1 Java Plugin to navigate between events posted by EventBus.

eventbus-intellij-plugin Plugin to navigate between events posted by EventBus. Post to onEvent and onEvent to Post Install There are two ways. Prefere

An Android library providing to realize wave loading effect.

WaveLoadingView WaveLoadingView - An Android library that provides a realistic wave-loading effect. Sample Usage For a working implementation of this

CustomMenu quickly realize about the menu
CustomMenu quickly realize about the menu

CustomMenu is a custom control that can help you quickly create Menu Features: Only the left menu Only the right menu Together with the right and left

Android library to realize the various states and transitions in a ProgressBar.
Android library to realize the various states and transitions in a ProgressBar.

StateProgressBar StateProgressBar is an Android library to realize the various states and transitions in a ProgressBar. Quick Start Get a feel of how

ViewModel LiveData Sample - Sample of using ViewModel, LiveData and Data Binding

ViewModel_LiveData_Sample Sample Code for Lesson 8 using ViewModel, LiveData and

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

Eventbus implemented by Flow

FlowBus FlowVersion EventBus Usage Add it in your root build.gradle at the end of repositories

EventBus for Android,消息总线,基于SharedFlow,具有生命周期感知能力,支持Sticky,支持线程切换,支持延迟发送。

背景 跨页面通信是一个比较常见的场景,通常我们会选择使用EventBus,但EventBus无法感知声明周期,收到消息就会回调,所以有了LiveData之后很快就有了LiveEventBus。不过它也有缺点,比如不能切换线程。

A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.
A lightweight eventbus library for android, simplifies communication between Activities, Fragments, Threads, Services, etc.

AndroidEventBus This is an EventBus library for Android. It simplifies the communication between Activities, Fragments, Threads, Services, etc. and lo

A Simple kotlin first EventBus implementation

EventBus Simple event bus for event-driven programming. Taking advantage of kotlin language features instead of typical reflections Table of Contents

MVVM(Model View ViewModel) sample in Kotlin using the components ViewModel, LiveData and Retrofit library
MVVM(Model View ViewModel) sample in Kotlin using the components ViewModel, LiveData and Retrofit library

kotlin-mvvm Languages: English, Spanish MVVM(Model View ViewModel) sample in Kotlin using the components ViewModel, LiveData, the libraries Retrofit,

A simple notes app to demo Room + LiveData implementation in Android
A simple notes app to demo Room + LiveData implementation in Android

RoomDb-Sample This is a demo app on how to implement Room persistance library, making use of LiveData in Android app How to implement Room: a SQLite o

Android To-Do MVVM Architecture App written in Kotlin.(ViewModel, ROOM, Livedata, Coroutines)

MVVM-To-Do-App A To-Do application written in kotlin using Android Architectural components What's new? Room + Coroutines - Upgraded Room to v2.1. Roo

❤️ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin)  architecture.
❤️ A sample Marvel heroes application based on MVVM (ViewModel, Coroutines, LiveData, Room, Repository, Koin) architecture.

MarvelHeroes MarvelHeroes is a demo application based on modern Android application tech-stacks and MVVM architecture. Fetching data from the network

🦁 A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, Flow, LiveData, Room, Repository, Koin) architecture.
🦁 A Disney app using transformation motions based on MVVM (ViewModel, Coroutines, Flow, LiveData, Room, Repository, Koin) architecture.

DisneyMotions A demo Disney app using transformation motions based on MVVM architecture. The motion system is included in the 1.2.0-alpha05 released m

Releases(1.1.0)
Owner
JaredDoge
JaredDoge
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
Android To-Do MVVM Architecture App written in Kotlin.(ViewModel, ROOM, Livedata, Coroutines)

MVVM-To-Do-App A To-Do application written in kotlin using Android Architectural components What's new? Room + Coroutines - Upgraded Room to v2.1. Roo

Naveen T P 77 Dec 8, 2022
Android Library for requesting Permissions with Kotlin Coroutines or AndroidX LiveData

PEKO PErmissions with KOtlin Android Permissions with Kotlin Coroutines or LiveData No more callbacks, builders, listeners or verbose code for request

Marko Devcic 133 Dec 14, 2022
Anime quotes rest api app with mvvm, LiveData, Coroutines, Navigation Component etc

AnimeQuote Anime quotes image rest api app with mvvm, LiveData, Coroutines, Navigation Component, clean achitecture etc An app created during mentorin

Ehma Ugbogo 4 Jun 11, 2021
Sample app that implements MVVM architecture using Kotlin, ViewModel, LiveData, and etc.

TheShard is a project to showcase different architectural approaches to developing Android apps. In its different branches you will find the same app (A movie Listing and detail page) implemented with small differences.

null 17 Aug 19, 2021
Wrapper of FusedLocationProviderClient for Android to support modern usage like LiveData and Flow

FancyLocationProvider Wrapper of FusedLocationProviderClient for Android to support modern usage like LiveData or Flow. Install Add Jitpack repository

Jintin 66 Aug 15, 2022
LiveData 数据倒灌:别问,问就是不可预期 - Perfect alternative to SingleLiveEvent, supporting multiple observers.

前言 大家好,我是《Jetpack MVVM Best Practice》作者 KunMinX。 今天提到的 “数据倒灌” 一词,缘于我为了方便理解和记忆 “页面在 ‘二进宫’ 时收到旧数据推送” 的情况,而在 2019 年 自创并在网上传播的 关于此类现象的概括。 它主要发生在:通过 Shared

KunMinX 924 Jan 5, 2023
Marvel Super Heroes | MVVM | Coroutines | DaggerHilt | LiveData

As an iOS developer, I'm learning Android and Kotlin trying to apply best practices, so I've started the same iOS project based on MARVEL, but now for ANDROID!

Míchel Marqués 2 Jun 4, 2022
Basic app to use different type of observables StateFlow, Flow, SharedFlow, LiveData, State, Channel...

stateflow-flow-sharedflow-livedata Basic app to use different type of observables StateFlow, Flow, SharedFlow, LiveData, State, Channel... StateFlow,

Raheem 5 Dec 21, 2022
ViewModel ve DataBindig ile LiveData kullanım örneği.

#Android Kotlin ViewModel ve Livedata Görsel Kaynak: https://www.youtube.com/watch?v=suC0OM5gGAA Temiz kod mantığı ve bu mantık doğrultusunda geliştir

Murat YÜKSEKTEPE 0 Nov 20, 2021