SlideShare a Scribd company logo
1 of 47
EventBus
for Android.
droidcon NL
23.11.2012
Markus Junginger


      © Copyright 2012 Markus Junginger.
                       All rights reserved.
Random Qoutes
Status Quo in Android
 Q: Who is talking to whom?
Status Quo in Android

                                   Activity



             Activity


                                       Service / Helper




  Fragment              Fragment                Thread
Communication Issues?!
 Tight coupling of components
   Inflexible, changes are expensive
 Boiler plate code
  – Define interfaces
  – Callbacks for asynch. communication
  – Listener management
  – Propagation through all layers
EventBus Communication

   Activity                  Activity



               Event
                Bus
                         Service / Helper




  Fragment    Fragment       Thread
EventBus for Android
   Event-based Publish/Subscribe
   Bus: central communication
   Inspired by Guava„s EventBus (Google)
   Android-optimized
   Open Source, Apache 2 License
    https://github.com/greenrobot/EventBus
EventBus in 4 Steps
1. Define an event

2. Register subscriber

3. Post an event

4. Receive the event
EventBus in 4 Steps: Code!
1. Define an event
  public class MyEvent {}
2. Register subscriber
  EventBus.getDefault().register(this);
3. Post an event
  EventBus.getDefault().post(event);
4. Receive the event
  public void onEvent(MyEvent event);
Publish / Subscribe


                                        Subscriber
                              Event
             Event    Event           onEvent()
 Publisher
             post()   Bus
                              Event

                                       Subscriber

                                      onEvent()
EventBus Instances
 EventBus instances
 Instances are indepent from each other
 For many apps, a single instance is fine
 „Convenience“ Instance
  EventBus.getDefault()
 Aquire it anywhere(!) in your code
Event Handler Method:
onEvent
 EventBus scans subscribers
  – During (first) registration of subscriber
  – For event handler methods
 Event handler methods
  – Naming convention: onEvent
  – public visibility
  – No return value (void)
  – Single parameter for the event to receive
Type-based Event Routing
 Event type: Java class of the event
 To receive an event, its type must match
 post(new MyEvent());
   onEvent(MyEvent event) {…}
 Type hierarchy of events
  – Implement logging of all events:
    onEvent(Object event)
Event Type is a Filter


                                           Subscriber
                                 Event
             Event       Event           onEvent(MyEvent)
 Publisher
             post        Bus
             (MyEvent)
                                          Subscriber

                                         onEvent(OtherEvent)
It„s time to see some

CODE
EventBus Code: Sender
MyEvent myEvent = new MyEvent(anyData);
EventBus.getDefault().post(myEvent);
EventBus Code: Receiver
MyActivity extends Activity // no interf.

// onCreate or onResume
EventBus.getDefault().register(this);

// onDestroy or onPause
EventBus.getDefault().unregister(this);

public onEvent(MyEvent event) { … }
Example: Fragment to
Fragment
   Tap on one fragment
   Another fragment reacts
   Typical list/details scenario
   Conventional setup:                Activity

    Activity is managing
    Fragments
                            Fragment              Fragment
Conventional: DetailFragment
// Here‘s the action. How is it called?
public void loadDetails(Item item) {
  …
}
Conventional: ListFragment
interface Contract {
     void onItemSelected(Item item);
}

// Propagate to Activity
((Contract)getActivity()).onItemSelected(item);
Conventional: Activity
public class MyActivity implements
ListFragment.Contract {

    public void onItemSelected(Item item) {
      DetailFragment detailFragment =
       (DetailFragment)
       getFragmentManager().findFragmentBy…;
      detailFragment.loadDetails(item);
    }
}
EventBus: Event class
public class ItemSelectedEvent {
  public final Item item;

    public ItemSelectedEvent(Item item) {
      this.item = item;
    }
}
EventBus: Post & Receive
// In ListFragment
EventBus.getDefault().post(new
     ItemSelectedEvent(item));



// In DetailFragment (extends EventBusFragment)
public void onEvent(ItemSelectedEvent event) {
…
}
Event Delivery in other Threads

THREADING SUPPORT
Why do Threads matter?
 Responsive UI, Android conventions
  – Main/UI thread must not block
  – UI updates in the main thread
  – Networking etc. in background threads
 Threads and Events
  – Thread posting events
  – Thread handling events
  – Posting and handling thread may differ
EventBus Threading Support
 Event delivery using threads
 Event handler method decides
  (handler knows best what it is doing)
 Naming conventions for onEvent methods
 To deliver in the main thread:
  onEventMainThread(…)
 (All methods beginning with onEvent are
  checked for typos)
Thread Modes
 PostThread: Direct call in same thread
 MainThread: UI updates etc.
 BackgroundThread: „not the main
  thread“
 Async: always asynchronous to posting
 Used in the method name: onEventXXX
 No additional code required
Threading Example
 Network thread posts result
 post(new UserLoginEvent(name));


 Fragment reacts to event in main thread
 public void
 onEventMainThread(UserLoginEvent e) {
   textView.setText(e.getName());
 }
Asynchronous execution and error dialogs

SNEAK PREVIEW
Upcoming: EventBus 2.1
 EventBus 2.1 is not final yet;
  Still gathering experience and feedback
 Everything pushed to master branch
 No relevant changes in the core (planned)
 Comes with some helpers
  – AsyncExecutor
  – Error dialog
EventBus 2.1: AsyncExecutor
 A thread pool, but with failure handling
 RunnableEx interface
  – Like Runnable to define code to run async.
  – May throw any execption
 ThrowableFailureEvent
  – Posted when exception occurs
  – Throwable object is wrapped inside
  – Subclass to customize and filter for type
AsyncExecutor: Calling Code
AsyncExecutor.create().execute(
  new RunnableEx {
    public void run throws LoginException {
      remote.login();
      EventBus.getDefault().postSticky(
        new LoggedInEvent());
      // No need to catch Exception
    }
  }
}
AsyncExecutor: Receiving
Code
public void
onEventMainThread(LoggedInEvent event) {
  // Change some UI
}
Comparison to AsyncTask
 AsyncExecutor advantages
  – Don‟t worry about configuration changes
    (typically device rotation)
  – Failure handling
  – EventBus (other dependencies somewhere?)
 AsyncTask advantage
  – Canceling task
EventBus 2.1: Error Dialog
 Operations may fail (networking, etc.)
 Some UI response should be shown
  – Currently: error dialogs
  – Later: Possibly maybe someth. Crouton-ish
 Multiple errors: don‟t open multiple times
 Goal: Minimize required code
How Error Dialogs work
 Error handling “attaches” to Activities
 Displaying dialogs is triggered by events
 ThrowableFailureEvent or subclass
  – AsyncExecutor sends those
  – Or post those events manually
Error Dialogs: Code
// In onCreate in your Activity
ErrorDialogManager.attachTo(this);

// Trigger the dialog
bus.post(new ThrowableFailureEvent(ex));
// Or let AsyncExecutor do it for you…
Dialog Configuration
 Which texts to display in the dialog?
 Simple option: Configure
  – Supply default resources for title and text
  – Map exception types  texts
 Flexible option: extend
  ErrorDialogFragmentFactory
Dialog Configuration: Code
// Initialize in your Application class
ErrorDialogConfig config = new
  ErrorDialogConfig(getResources(),
    R.string.error_generalTitle,
    R.string.error_general);
config.addMapping(UnknownHostException.class,
  R.string.error_noInternetConnection);
config.addMapping(IOException.class,
  R.string.error_generalServer);
ErrorDialogManager.factory = new
  ErrorDialogFragmentFactory.Support(config);
Comparison Android
Broadcast
 Nice, but somewhat inconvenient
 BroadcastReceiver has to be extended
 Registration needed for every event type
 Extra work to filter for desired event types
  (IntentFilter with e.g. ACTION String)
 Data is converted into Intent extras
Tiny bits and some other stuff

TIPPS AND SNIPPS
Sticky Events
 Events can be posted using sticky mode
 postSticky(event); // Instead of post(…)
 The last sticky event is kept in memory
 Registration with getting sticky events
 registerSticky(subscriber);
 Query for sticky event
 getStickyEvent(Class<?> eventType)
 Remove sticky event (Class or Object)
 removeStickyEvent(Class<?> eventType)
Events Class
 Event classes are tiny; group them

public class Events {
  public static class InitThreadCompleteEvent {
  }

    public static class LoginCompleteEvent {
    }
}
EventBusFragment/-Activity
 Superclass depends on your setup
 Implement in your project
 class EventBusFragment extends Fragment {
 public void onCreate(…) {
   super.onCreate(…);
   EventBus.getDefault().register(this);
 }
 public void onDestroy() {
   EventBus.getDefault().unregister(this);
   super.onDestroy();
 }
When to use EventBus
 Medium/high distance of components:
  “Somewhere” else should happen sth.
 Potentially multiple dependencies
 Asynchronous logic
 When not to use EventBus
  – Strictly internal matters:
    Use methods and interfaces instead
  – Inter-process communication
License, Contact
 This presentation is licensed under
  CreativeCommons ShareAlike/Attribution
 http://creativecommons.org/licenses/by-sa/3.0/


 Contact greenrobot
  – http://greenrobot.de
  – http://twitter.com/greenrobot_de
  – Google+: http://bit.ly/greenrobotplus

More Related Content

What's hot

Project presentation FPS
Project presentation FPSProject presentation FPS
Project presentation FPSShubham Rajput
 
Unityネイティブプラグインの勧め
Unityネイティブプラグインの勧めUnityネイティブプラグインの勧め
Unityネイティブプラグインの勧めKLab Inc. / Tech
 
Binderのはじめの一歩とAndroid
Binderのはじめの一歩とAndroidBinderのはじめの一歩とAndroid
Binderのはじめの一歩とAndroidl_b__
 
Multiplayer Networking Game
Multiplayer Networking GameMultiplayer Networking Game
Multiplayer Networking GameTanmay Krishna
 
Unite2019 _ 학교에서 배우는 게임개발이란
Unite2019 _ 학교에서 배우는 게임개발이란Unite2019 _ 학교에서 배우는 게임개발이란
Unite2019 _ 학교에서 배우는 게임개발이란JP Jung
 
フロントエンドで GraphQLを使った所感
フロントエンドで GraphQLを使った所感フロントエンドで GraphQLを使った所感
フロントエンドで GraphQLを使った所感Chao Li
 
NDC2019 - 게임플레이 프로그래머의 역할
NDC2019 - 게임플레이 프로그래머의 역할NDC2019 - 게임플레이 프로그래머의 역할
NDC2019 - 게임플레이 프로그래머의 역할Hoyoung Choi
 
software effort estimation
 software effort estimation software effort estimation
software effort estimationBesharam Dil
 
Control Flow Graphs
Control Flow GraphsControl Flow Graphs
Control Flow Graphsdaimk2020
 
パタヘネゼミ 第6章
パタヘネゼミ 第6章パタヘネゼミ 第6章
パタヘネゼミ 第6章okuraofvegetable
 
CRC-32
CRC-32CRC-32
CRC-327shi
 
ECS (Part 1/3) - Introduction to Data-Oriented Design
ECS (Part 1/3) - Introduction to Data-Oriented DesignECS (Part 1/3) - Introduction to Data-Oriented Design
ECS (Part 1/3) - Introduction to Data-Oriented DesignPhuong Hoang Vu
 
liftIO 2022 quasiquote
liftIO 2022 quasiquoteliftIO 2022 quasiquote
liftIO 2022 quasiquoteHyunseok Cho
 
C#言語機能の作り方
C#言語機能の作り方C#言語機能の作り方
C#言語機能の作り方信之 岩永
 
ゴリラテスト モバイルゲームのUIを自動的に検出・操作する モンキーテスト
ゴリラテスト  モバイルゲームのUIを自動的に検出・操作する モンキーテストゴリラテスト  モバイルゲームのUIを自動的に検出・操作する モンキーテスト
ゴリラテスト モバイルゲームのUIを自動的に検出・操作する モンキーテストKLab Inc. / Tech
 
Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2YEONG-CHEON YOU
 
Design phase of game development of unity 2d game
Design phase of game development of unity 2d game Design phase of game development of unity 2d game
Design phase of game development of unity 2d game Muhammad Maaz Irfan
 
신입 SW 개발자 취업 준비
신입 SW 개발자 취업 준비신입 SW 개발자 취업 준비
신입 SW 개발자 취업 준비인서 박
 

What's hot (20)

Project presentation FPS
Project presentation FPSProject presentation FPS
Project presentation FPS
 
Unityネイティブプラグインの勧め
Unityネイティブプラグインの勧めUnityネイティブプラグインの勧め
Unityネイティブプラグインの勧め
 
Binderのはじめの一歩とAndroid
Binderのはじめの一歩とAndroidBinderのはじめの一歩とAndroid
Binderのはじめの一歩とAndroid
 
Multiplayer Networking Game
Multiplayer Networking GameMultiplayer Networking Game
Multiplayer Networking Game
 
Unite2019 _ 학교에서 배우는 게임개발이란
Unite2019 _ 학교에서 배우는 게임개발이란Unite2019 _ 학교에서 배우는 게임개발이란
Unite2019 _ 학교에서 배우는 게임개발이란
 
フロントエンドで GraphQLを使った所感
フロントエンドで GraphQLを使った所感フロントエンドで GraphQLを使った所感
フロントエンドで GraphQLを使った所感
 
NDC2019 - 게임플레이 프로그래머의 역할
NDC2019 - 게임플레이 프로그래머의 역할NDC2019 - 게임플레이 프로그래머의 역할
NDC2019 - 게임플레이 프로그래머의 역할
 
software effort estimation
 software effort estimation software effort estimation
software effort estimation
 
Control Flow Graphs
Control Flow GraphsControl Flow Graphs
Control Flow Graphs
 
パタヘネゼミ 第6章
パタヘネゼミ 第6章パタヘネゼミ 第6章
パタヘネゼミ 第6章
 
CRC-32
CRC-32CRC-32
CRC-32
 
ECS (Part 1/3) - Introduction to Data-Oriented Design
ECS (Part 1/3) - Introduction to Data-Oriented DesignECS (Part 1/3) - Introduction to Data-Oriented Design
ECS (Part 1/3) - Introduction to Data-Oriented Design
 
Programming with LEX & YACC
Programming with LEX & YACCProgramming with LEX & YACC
Programming with LEX & YACC
 
liftIO 2022 quasiquote
liftIO 2022 quasiquoteliftIO 2022 quasiquote
liftIO 2022 quasiquote
 
C#言語機能の作り方
C#言語機能の作り方C#言語機能の作り方
C#言語機能の作り方
 
ゴリラテスト モバイルゲームのUIを自動的に検出・操作する モンキーテスト
ゴリラテスト  モバイルゲームのUIを自動的に検出・操作する モンキーテストゴリラテスト  モバイルゲームのUIを自動的に検出・操作する モンキーテスト
ゴリラテスト モバイルゲームのUIを自動的に検出・操作する モンキーテスト
 
Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2Visual Studio를 이용한 어셈블리어 학습 part 2
Visual Studio를 이용한 어셈블리어 학습 part 2
 
Design phase of game development of unity 2d game
Design phase of game development of unity 2d game Design phase of game development of unity 2d game
Design phase of game development of unity 2d game
 
Software project management 3
Software project management 3Software project management 3
Software project management 3
 
신입 SW 개발자 취업 준비
신입 SW 개발자 취업 준비신입 SW 개발자 취업 준비
신입 SW 개발자 취업 준비
 

Similar to EventBus for Android

Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Elizabeth Smith
 
Event and signal driven programming
Event and signal driven programmingEvent and signal driven programming
Event and signal driven programmingElizabeth Smith
 
Java gui event
Java gui eventJava gui event
Java gui eventSoftNutx
 
Event bus for android
Event bus for androidEvent bus for android
Event bus for android丞廷 鄭
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handlingAmol Gaikwad
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Nida Ismail Shah
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfJEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfMarlouFelixIIICunana
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingPayal Dungarwal
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)jammiashok123
 
Java event processing model in c# and java
Java  event processing model in c# and javaJava  event processing model in c# and java
Java event processing model in c# and javaTech_MX
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 
A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015Matthias Noback
 

Similar to EventBus for Android (20)

GreenRobot-Eventbus
GreenRobot-EventbusGreenRobot-Eventbus
GreenRobot-Eventbus
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012
 
Event and signal driven programming
Event and signal driven programmingEvent and signal driven programming
Event and signal driven programming
 
Java gui event
Java gui eventJava gui event
Java gui event
 
Event bus for android
Event bus for androidEvent bus for android
Event bus for android
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Javascript Browser Events.pdf
Javascript Browser Events.pdfJavascript Browser Events.pdf
Javascript Browser Events.pdf
 
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfJEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
dSS API by example
dSS API by exampledSS API by example
dSS API by example
 
GWT MVP Case Study
GWT MVP Case StudyGWT MVP Case Study
GWT MVP Case Study
 
WPF Fundamentals
WPF FundamentalsWPF Fundamentals
WPF Fundamentals
 
Java event processing model in c# and java
Java  event processing model in c# and javaJava  event processing model in c# and java
Java event processing model in c# and java
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015A Series of Fortunate Events - PHP Benelux Conference 2015
A Series of Fortunate Events - PHP Benelux Conference 2015
 

Recently uploaded

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Recently uploaded (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

EventBus for Android

  • 1. EventBus for Android. droidcon NL 23.11.2012 Markus Junginger © Copyright 2012 Markus Junginger. All rights reserved.
  • 2.
  • 4. Status Quo in Android  Q: Who is talking to whom?
  • 5. Status Quo in Android Activity Activity Service / Helper Fragment Fragment Thread
  • 6. Communication Issues?!  Tight coupling of components  Inflexible, changes are expensive  Boiler plate code – Define interfaces – Callbacks for asynch. communication – Listener management – Propagation through all layers
  • 7. EventBus Communication Activity Activity Event Bus Service / Helper Fragment Fragment Thread
  • 8. EventBus for Android  Event-based Publish/Subscribe  Bus: central communication  Inspired by Guava„s EventBus (Google)  Android-optimized  Open Source, Apache 2 License https://github.com/greenrobot/EventBus
  • 9. EventBus in 4 Steps 1. Define an event 2. Register subscriber 3. Post an event 4. Receive the event
  • 10. EventBus in 4 Steps: Code! 1. Define an event public class MyEvent {} 2. Register subscriber EventBus.getDefault().register(this); 3. Post an event EventBus.getDefault().post(event); 4. Receive the event public void onEvent(MyEvent event);
  • 11. Publish / Subscribe Subscriber Event Event Event onEvent() Publisher post() Bus Event Subscriber onEvent()
  • 12. EventBus Instances  EventBus instances  Instances are indepent from each other  For many apps, a single instance is fine  „Convenience“ Instance EventBus.getDefault()  Aquire it anywhere(!) in your code
  • 13. Event Handler Method: onEvent  EventBus scans subscribers – During (first) registration of subscriber – For event handler methods  Event handler methods – Naming convention: onEvent – public visibility – No return value (void) – Single parameter for the event to receive
  • 14. Type-based Event Routing  Event type: Java class of the event  To receive an event, its type must match  post(new MyEvent());  onEvent(MyEvent event) {…}  Type hierarchy of events – Implement logging of all events: onEvent(Object event)
  • 15. Event Type is a Filter Subscriber Event Event Event onEvent(MyEvent) Publisher post Bus (MyEvent) Subscriber onEvent(OtherEvent)
  • 16. It„s time to see some CODE
  • 17. EventBus Code: Sender MyEvent myEvent = new MyEvent(anyData); EventBus.getDefault().post(myEvent);
  • 18. EventBus Code: Receiver MyActivity extends Activity // no interf. // onCreate or onResume EventBus.getDefault().register(this); // onDestroy or onPause EventBus.getDefault().unregister(this); public onEvent(MyEvent event) { … }
  • 19. Example: Fragment to Fragment  Tap on one fragment  Another fragment reacts  Typical list/details scenario  Conventional setup: Activity Activity is managing Fragments Fragment Fragment
  • 20. Conventional: DetailFragment // Here‘s the action. How is it called? public void loadDetails(Item item) { … }
  • 21. Conventional: ListFragment interface Contract { void onItemSelected(Item item); } // Propagate to Activity ((Contract)getActivity()).onItemSelected(item);
  • 22. Conventional: Activity public class MyActivity implements ListFragment.Contract { public void onItemSelected(Item item) { DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentBy…; detailFragment.loadDetails(item); } }
  • 23. EventBus: Event class public class ItemSelectedEvent { public final Item item; public ItemSelectedEvent(Item item) { this.item = item; } }
  • 24. EventBus: Post & Receive // In ListFragment EventBus.getDefault().post(new ItemSelectedEvent(item)); // In DetailFragment (extends EventBusFragment) public void onEvent(ItemSelectedEvent event) { … }
  • 25. Event Delivery in other Threads THREADING SUPPORT
  • 26. Why do Threads matter?  Responsive UI, Android conventions – Main/UI thread must not block – UI updates in the main thread – Networking etc. in background threads  Threads and Events – Thread posting events – Thread handling events – Posting and handling thread may differ
  • 27. EventBus Threading Support  Event delivery using threads  Event handler method decides (handler knows best what it is doing)  Naming conventions for onEvent methods  To deliver in the main thread: onEventMainThread(…)  (All methods beginning with onEvent are checked for typos)
  • 28. Thread Modes  PostThread: Direct call in same thread  MainThread: UI updates etc.  BackgroundThread: „not the main thread“  Async: always asynchronous to posting  Used in the method name: onEventXXX  No additional code required
  • 29. Threading Example  Network thread posts result post(new UserLoginEvent(name));  Fragment reacts to event in main thread public void onEventMainThread(UserLoginEvent e) { textView.setText(e.getName()); }
  • 30. Asynchronous execution and error dialogs SNEAK PREVIEW
  • 31. Upcoming: EventBus 2.1  EventBus 2.1 is not final yet; Still gathering experience and feedback  Everything pushed to master branch  No relevant changes in the core (planned)  Comes with some helpers – AsyncExecutor – Error dialog
  • 32. EventBus 2.1: AsyncExecutor  A thread pool, but with failure handling  RunnableEx interface – Like Runnable to define code to run async. – May throw any execption  ThrowableFailureEvent – Posted when exception occurs – Throwable object is wrapped inside – Subclass to customize and filter for type
  • 33. AsyncExecutor: Calling Code AsyncExecutor.create().execute( new RunnableEx { public void run throws LoginException { remote.login(); EventBus.getDefault().postSticky( new LoggedInEvent()); // No need to catch Exception } } }
  • 35. Comparison to AsyncTask  AsyncExecutor advantages – Don‟t worry about configuration changes (typically device rotation) – Failure handling – EventBus (other dependencies somewhere?)  AsyncTask advantage – Canceling task
  • 36. EventBus 2.1: Error Dialog  Operations may fail (networking, etc.)  Some UI response should be shown – Currently: error dialogs – Later: Possibly maybe someth. Crouton-ish  Multiple errors: don‟t open multiple times  Goal: Minimize required code
  • 37. How Error Dialogs work  Error handling “attaches” to Activities  Displaying dialogs is triggered by events  ThrowableFailureEvent or subclass – AsyncExecutor sends those – Or post those events manually
  • 38. Error Dialogs: Code // In onCreate in your Activity ErrorDialogManager.attachTo(this); // Trigger the dialog bus.post(new ThrowableFailureEvent(ex)); // Or let AsyncExecutor do it for you…
  • 39. Dialog Configuration  Which texts to display in the dialog?  Simple option: Configure – Supply default resources for title and text – Map exception types  texts  Flexible option: extend ErrorDialogFragmentFactory
  • 40. Dialog Configuration: Code // Initialize in your Application class ErrorDialogConfig config = new ErrorDialogConfig(getResources(), R.string.error_generalTitle, R.string.error_general); config.addMapping(UnknownHostException.class, R.string.error_noInternetConnection); config.addMapping(IOException.class, R.string.error_generalServer); ErrorDialogManager.factory = new ErrorDialogFragmentFactory.Support(config);
  • 41. Comparison Android Broadcast  Nice, but somewhat inconvenient  BroadcastReceiver has to be extended  Registration needed for every event type  Extra work to filter for desired event types (IntentFilter with e.g. ACTION String)  Data is converted into Intent extras
  • 42. Tiny bits and some other stuff TIPPS AND SNIPPS
  • 43. Sticky Events  Events can be posted using sticky mode postSticky(event); // Instead of post(…)  The last sticky event is kept in memory  Registration with getting sticky events registerSticky(subscriber);  Query for sticky event getStickyEvent(Class<?> eventType)  Remove sticky event (Class or Object) removeStickyEvent(Class<?> eventType)
  • 44. Events Class  Event classes are tiny; group them public class Events { public static class InitThreadCompleteEvent { } public static class LoginCompleteEvent { } }
  • 45. EventBusFragment/-Activity  Superclass depends on your setup  Implement in your project class EventBusFragment extends Fragment { public void onCreate(…) { super.onCreate(…); EventBus.getDefault().register(this); } public void onDestroy() { EventBus.getDefault().unregister(this); super.onDestroy(); }
  • 46. When to use EventBus  Medium/high distance of components: “Somewhere” else should happen sth.  Potentially multiple dependencies  Asynchronous logic  When not to use EventBus – Strictly internal matters: Use methods and interfaces instead – Inter-process communication
  • 47. License, Contact  This presentation is licensed under CreativeCommons ShareAlike/Attribution http://creativecommons.org/licenses/by-sa/3.0/  Contact greenrobot – http://greenrobot.de – http://twitter.com/greenrobot_de – Google+: http://bit.ly/greenrobotplus