SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
Dalvik Android  Talks
Event Bus
Android  Developer
Gokhan  Arik
Jun  27,  2016
www.gokhanarik.com
Introduction
● What  is  an  Event  Bus?
● Callback  vs  Broadcast  Receiver  vs  Event  Bus
● Event  Bus  Libraries  for  Android
▪ Otto  by  Square  (deprecated   on  January  15,  2016)
▪ EventBus  by  greenrobot
▪ RxJava  by  ReactiveX
● Q/A
● References
What  is  an  Event  Bus?
● System  Bus
● Central  hub
● Flexible  and  modular
What  is  an  Event  Bus?
How  can  I  pass  value  from  X  to  Y  when  click  on  Z?
● Callback  (a.k.a  Listener)
● Broadcast  Receiver
● Event  Bus
What  is  an  Event  Bus?
Common  Crash  in  Android
java.lang.IllegalStateException:  Can  not perform  this  action  after  onSaveInstanceState
at  android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at  android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at  android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at  android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
What  is  an  Event  Bus?
Callback
/**
*  Interface   definition   for  a  callback   to  be  invoked   when   a  view  is  clicked.
*/
public interface OnClickListener {
/**
*  Called   when   a  view  has  been   clicked.
*
*  @param v  The  view   that  was  clicked.
*/
void onClick(View v);
}
What  is  an  Event  Bus?
Broadcast  Receiver
private MyReceiver mReceiver;
void onResume()   {
IntentFilter filter   = new IntentFilter("com.example.MyEvent");
mReceiver   = new MyReceiver();
registerReceiver(receiver,   filter);
}
void onPause()   {
unregisterReceiver(mReceiver);
}
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context,   Intent intent)   {
Toast.makeText(context,   "MyEvent",   Toast.LENGTH_LONG).show();
}
}
}
What  is  an  Event  Bus?
Broadcast  Receiver
public void sendBroadcast()   {
Intent   intent   = new Intent("com.example.MyEvent");
intent.putExtra("myParam",   "Hello");
sendBroadcast(intent);
}
What  is  an  Event  Bus?
Event  Bus
● Publish  &  Subscribe  Pattern  implementation  (similar  to  Observable)
● Component  to  component  communication  without  direct  reference
● Three  well-­known  libraries  for  Android
▪ Otto  by  Square  (deprecated   on  January  15,  2016)
▪ EventBus  by  greenrobot
▪ RxJava  by  ReactiveX
What  is  an  Event  Bus?
Event  Bus
Callback  vs  Broadcast  Receiver  vs  Event  Bus
Callback
Pros
● Easy  to  implement  for  small  projects
Cons
● Excessive  amount  of  boilerplate  code
● Unnecessary  method  overrides
Callback  vs  Broadcast  Receiver  vs  Event  Bus
Broadcast  Receiver
Pros
● Native  solution  to  problem
▪ Consistency  in  the  code
Cons
● Too  much  code  for  a  simple  task
Callback  vs  Broadcast  Receiver  vs  Event  Bus
Event  Bus
Pros
● Cleaner,  maintainable,  extensible,  flexible  and  more  readable  code
● Easier  to  test
● Multiple  receivers
● Subscribing  to  events  you  need
● No  direct  reference  between  components
Cons
● Hard  to  maintain  list  of  publishers  (fewer  publisher  recommended)  
● No  auto-­complete  support  from  IDE
● Powerful  but  easily  can  be  abused
Otto  by  Square
Event  Bus  Libraries  for  Android
● Fork  of  Guava  based  Event  Bus
● Designed  for  Android
● Deprecated  on  January  15,  2016
Otto  by  Square
Event  Bus  Libraries  for  Android
public class UpdateDataEvent {
public String data;
public UpdateDataEvent(String data)  {
this.data  = data;
}
}
Otto  by  Square
Event  Bus  Libraries  for  Android
//  Use  as  a  singleton
Bus bus  = new Bus();
//  Publish  an  event.  Posting  to  the  bus  is  a  synchronous  action.
bus.post(new UpdateDataEvent("New  Data!"));
//  Subscribe  to  a  specific  event.  Any  method  name.  As  long  as  annotated  with  @Subscribe
@Subscribe
public void dataUpdated(UpdateDataEvent event)  {
//  React  to  the  event  (ex.  update  UI,  save  data  to  database)
Log.v(TAG,  "Data:  " + event.data);
}
Otto  by  Square
Event  Bus  Libraries  for  Android
//  Register  your  class
bus.register(this);  //  inside  onStart()  method
bus.unregister(this);  //  inside  onStop()  method
//  Produce
@Produce
public UpdateDataEvent produceDataUpdate()  {
//  Assuming  data  exists.
return new AnswerAvailableEvent(this.data);
}
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
● Developers  of  greenDAO
● Same  basic  semantics  as  Otto
● Faster  than  Otto
● Richer  feature  set  
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
public class UpdateDataEvent {
public String data;
public UpdateDataEvent(String data)  {
this.data  = data;
}
}
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
//  Similar  to  Otto
EventBus bus  = EventBus.getDefault();
//  With  richer  feature  set
EventBus bus  = EventBus.builder().logNoSubscriberMessages(false).sendNoSubscriberEvent(false).build();
EventBus bus  = EventBus.builder().throwSubscriberException(true).build();
//  Must  be  called  once.  FOr  example,  in  Application  class’  onCreate()  method
EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).installDefaultEventBus();
//  Publish  an  event
bus.post(new UpdateDataEvent("New  data!"));
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
//  Register  your  class
bus.register(this);  //  inside  onStart()  method
bus.unregister(this);  //  inside  onStop()  method
//  Subscribe  to  a  specific  event.  Any  method  name.  As  long  as  annotated  with  @Subscribe
@Subscribe
public void dataUpdated(UpdateDataEvent event)  {
//  React  to  the  event  (ex.  update  UI,  save  data  to  database)
Log.v(TAG,  "Data:  " + event.data);
}
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
@Subscribe(threadMode  = ThreadMode.POSTING)  //  Opt.
public void onMessage(MessageEvent event)  {
log(event.message);
}
ThreadMode
● POSTING
▪ Default  ThreadMode
▪ Good  for  simple  tasks
● MAIN
▪ Runs  on  main/UI  thread
● BACKGROUND
● ASYNC @Subscribe(threadMode  = ThreadMode.BACKGROUND)
public void onMessage(MessageEvent event){
saveToDisk(event.message);
}
@Subscribe(threadMode  = ThreadMode.MAIN)
public void onMessage(MessageEvent event)  {
textField.setText(event.message);
}
EventBus  by  greenrobot
Event  Bus  Libraries  for  Android
//  Posting   a  Sticky   Event
bus.postSticky(new LastLocationEvent("Omaha!"));
Sticky  Events
● Last  sticky  event  kept  in  memory
● Delivered  to  subscriber  as  soon  as  
registered
@Override
public void onStart()   {
super.onStart();
bus.register(this);
}
@Subscribe(sticky   = true,   threadMode   = ThreadMode.MAIN)
public void onEvent(LastLocationEvent event)   {
textField.setText(event.message);
}
@Override
public void onStop()   {
bus.unregister(this);
super.onStop();
}
RxJava  by  ReactiveX
Event  Bus  Libraries  for  Android
//  this  is  the  middleman  object
public class RxBus {
private Subject<Object,  Object> bus  = new
SerializedSubject<>(PublishSubject.create());
public void send(Object o)  {
bus.onNext(o);
}
public Observable<Object> toObserverable()  {
return bus;
}
}
@OnClick(R.id.btn_demo_rxbus_tap)
public void onTapButtonClicked()   {
bus.send(new TapEvent());
}
bus.toObserverable()
.subscribe(new Action1<Object>()   {
@Override
public void call(Object event)   {
if(event   instanceof TapEvent)   {
_showTapText();
}else if(event   instanceof SomeOtherEvent)   {
_doSomethingElse();
}
}
});
Dalvik  Android  Talks
Q/A
Dalvik  Android  Talks
Thank  You
References
1. https://github.com/square/otto-­intellij-­plugin
2. http://cases.azoft.com/message-­bus-­in-­android-­apps/
3. http://poohdish.ghost.io/what-­is-­event-­bus/
4. http://timnew.me/blog/2014/12/06/typical-­eventbus-­design-­patterns/
5. https://github.com/greenrobot/EventBus/blob/master/COMPARISON.md
6. http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-­an-­event-­bus-­with-­rxjava-­rxbus/
7. https://github.com/greenrobot/EventBus
8. https://github.com/kaushikgopal/RxJava-­Android-­
Samples/blob/master/app/src/main/java/com/morihacky/android/rxjava/rxbus

Weitere ähnliche Inhalte

Ähnlich wie Event Bus by Gokhan Arik - Dalvik Android Talks at CRi

Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 
Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2JooinK
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Mahmoud Hamed Mahmoud
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitIMC Institute
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Androidgreenrobot
 
Web polyglot programming
Web polyglot programmingWeb polyglot programming
Web polyglot programmingDmitry Buzdin
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTudor Barbu
 
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...Matt Spradley
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web developmentalice yang
 
An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAndrei Sebastian Cîmpean
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application developmentEngin Hatay
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Enginecatherinewall
 
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...COMAQA.BY
 
Writing java script for Csharp's Blazor
Writing java script for Csharp's BlazorWriting java script for Csharp's Blazor
Writing java script for Csharp's BlazorEd Charbeneau
 
Easing offline web application development with GWT
Easing offline web application development with GWTEasing offline web application development with GWT
Easing offline web application development with GWTArnaud Tournier
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 

Ähnlich wie Event Bus by Gokhan Arik - Dalvik Android Talks at CRi (20)

Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2Javascript as a target language - GWT KickOff - Part 2/2
Javascript as a target language - GWT KickOff - Part 2/2
 
Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development Windows Store app using XAML and C#: Enterprise Product Development
Windows Store app using XAML and C#: Enterprise Product Development
 
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web ToolkitJava Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Android
 
Web polyglot programming
Web polyglot programmingWeb polyglot programming
Web polyglot programming
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
 
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
How We Built a Mobile Electronic Health Record App Using Xamarin, Angular, an...
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile Services
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
 
An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSockets
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application development
 
GWT
GWTGWT
GWT
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
Тестирование мобильных приложений используя облачные сервисы. TestDroid, Test...
 
Writing java script for Csharp's Blazor
Writing java script for Csharp's BlazorWriting java script for Csharp's Blazor
Writing java script for Csharp's Blazor
 
Easing offline web application development with GWT
Easing offline web application development with GWTEasing offline web application development with GWT
Easing offline web application development with GWT
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 

Kürzlich hochgeladen

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Kürzlich hochgeladen (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

Event Bus by Gokhan Arik - Dalvik Android Talks at CRi

  • 1. Dalvik Android  Talks Event Bus Android  Developer Gokhan  Arik Jun  27,  2016 www.gokhanarik.com
  • 2. Introduction ● What  is  an  Event  Bus? ● Callback  vs  Broadcast  Receiver  vs  Event  Bus ● Event  Bus  Libraries  for  Android ▪ Otto  by  Square  (deprecated   on  January  15,  2016) ▪ EventBus  by  greenrobot ▪ RxJava  by  ReactiveX ● Q/A ● References
  • 3. What  is  an  Event  Bus? ● System  Bus ● Central  hub ● Flexible  and  modular
  • 4. What  is  an  Event  Bus? How  can  I  pass  value  from  X  to  Y  when  click  on  Z? ● Callback  (a.k.a  Listener) ● Broadcast  Receiver ● Event  Bus
  • 5. What  is  an  Event  Bus? Common  Crash  in  Android java.lang.IllegalStateException:  Can  not perform  this  action  after  onSaveInstanceState at  android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341) at  android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352) at  android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595) at  android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
  • 6. What  is  an  Event  Bus? Callback /** *  Interface   definition   for  a  callback   to  be  invoked   when   a  view  is  clicked. */ public interface OnClickListener { /** *  Called   when   a  view  has  been   clicked. * *  @param v  The  view   that  was  clicked. */ void onClick(View v); }
  • 7. What  is  an  Event  Bus? Broadcast  Receiver private MyReceiver mReceiver; void onResume()   { IntentFilter filter   = new IntentFilter("com.example.MyEvent"); mReceiver   = new MyReceiver(); registerReceiver(receiver,   filter); } void onPause()   { unregisterReceiver(mReceiver); } public class MyReceiver extends BroadcastReceiver { public void onReceive(Context context,   Intent intent)   { Toast.makeText(context,   "MyEvent",   Toast.LENGTH_LONG).show(); } } }
  • 8. What  is  an  Event  Bus? Broadcast  Receiver public void sendBroadcast()   { Intent   intent   = new Intent("com.example.MyEvent"); intent.putExtra("myParam",   "Hello"); sendBroadcast(intent); }
  • 9. What  is  an  Event  Bus? Event  Bus ● Publish  &  Subscribe  Pattern  implementation  (similar  to  Observable) ● Component  to  component  communication  without  direct  reference ● Three  well-­known  libraries  for  Android ▪ Otto  by  Square  (deprecated   on  January  15,  2016) ▪ EventBus  by  greenrobot ▪ RxJava  by  ReactiveX
  • 10. What  is  an  Event  Bus? Event  Bus
  • 11. Callback  vs  Broadcast  Receiver  vs  Event  Bus Callback Pros ● Easy  to  implement  for  small  projects Cons ● Excessive  amount  of  boilerplate  code ● Unnecessary  method  overrides
  • 12. Callback  vs  Broadcast  Receiver  vs  Event  Bus Broadcast  Receiver Pros ● Native  solution  to  problem ▪ Consistency  in  the  code Cons ● Too  much  code  for  a  simple  task
  • 13. Callback  vs  Broadcast  Receiver  vs  Event  Bus Event  Bus Pros ● Cleaner,  maintainable,  extensible,  flexible  and  more  readable  code ● Easier  to  test ● Multiple  receivers ● Subscribing  to  events  you  need ● No  direct  reference  between  components Cons ● Hard  to  maintain  list  of  publishers  (fewer  publisher  recommended)   ● No  auto-­complete  support  from  IDE ● Powerful  but  easily  can  be  abused
  • 14. Otto  by  Square Event  Bus  Libraries  for  Android ● Fork  of  Guava  based  Event  Bus ● Designed  for  Android ● Deprecated  on  January  15,  2016
  • 15. Otto  by  Square Event  Bus  Libraries  for  Android public class UpdateDataEvent { public String data; public UpdateDataEvent(String data)  { this.data  = data; } }
  • 16. Otto  by  Square Event  Bus  Libraries  for  Android //  Use  as  a  singleton Bus bus  = new Bus(); //  Publish  an  event.  Posting  to  the  bus  is  a  synchronous  action. bus.post(new UpdateDataEvent("New  Data!")); //  Subscribe  to  a  specific  event.  Any  method  name.  As  long  as  annotated  with  @Subscribe @Subscribe public void dataUpdated(UpdateDataEvent event)  { //  React  to  the  event  (ex.  update  UI,  save  data  to  database) Log.v(TAG,  "Data:  " + event.data); }
  • 17. Otto  by  Square Event  Bus  Libraries  for  Android //  Register  your  class bus.register(this);  //  inside  onStart()  method bus.unregister(this);  //  inside  onStop()  method //  Produce @Produce public UpdateDataEvent produceDataUpdate()  { //  Assuming  data  exists. return new AnswerAvailableEvent(this.data); }
  • 18. EventBus  by  greenrobot Event  Bus  Libraries  for  Android ● Developers  of  greenDAO ● Same  basic  semantics  as  Otto ● Faster  than  Otto ● Richer  feature  set  
  • 19. EventBus  by  greenrobot Event  Bus  Libraries  for  Android public class UpdateDataEvent { public String data; public UpdateDataEvent(String data)  { this.data  = data; } }
  • 20. EventBus  by  greenrobot Event  Bus  Libraries  for  Android //  Similar  to  Otto EventBus bus  = EventBus.getDefault(); //  With  richer  feature  set EventBus bus  = EventBus.builder().logNoSubscriberMessages(false).sendNoSubscriberEvent(false).build(); EventBus bus  = EventBus.builder().throwSubscriberException(true).build(); //  Must  be  called  once.  FOr  example,  in  Application  class’  onCreate()  method EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).installDefaultEventBus(); //  Publish  an  event bus.post(new UpdateDataEvent("New  data!"));
  • 21. EventBus  by  greenrobot Event  Bus  Libraries  for  Android //  Register  your  class bus.register(this);  //  inside  onStart()  method bus.unregister(this);  //  inside  onStop()  method //  Subscribe  to  a  specific  event.  Any  method  name.  As  long  as  annotated  with  @Subscribe @Subscribe public void dataUpdated(UpdateDataEvent event)  { //  React  to  the  event  (ex.  update  UI,  save  data  to  database) Log.v(TAG,  "Data:  " + event.data); }
  • 22. EventBus  by  greenrobot Event  Bus  Libraries  for  Android @Subscribe(threadMode  = ThreadMode.POSTING)  //  Opt. public void onMessage(MessageEvent event)  { log(event.message); } ThreadMode ● POSTING ▪ Default  ThreadMode ▪ Good  for  simple  tasks ● MAIN ▪ Runs  on  main/UI  thread ● BACKGROUND ● ASYNC @Subscribe(threadMode  = ThreadMode.BACKGROUND) public void onMessage(MessageEvent event){ saveToDisk(event.message); } @Subscribe(threadMode  = ThreadMode.MAIN) public void onMessage(MessageEvent event)  { textField.setText(event.message); }
  • 23. EventBus  by  greenrobot Event  Bus  Libraries  for  Android //  Posting   a  Sticky   Event bus.postSticky(new LastLocationEvent("Omaha!")); Sticky  Events ● Last  sticky  event  kept  in  memory ● Delivered  to  subscriber  as  soon  as   registered @Override public void onStart()   { super.onStart(); bus.register(this); } @Subscribe(sticky   = true,   threadMode   = ThreadMode.MAIN) public void onEvent(LastLocationEvent event)   { textField.setText(event.message); } @Override public void onStop()   { bus.unregister(this); super.onStop(); }
  • 24. RxJava  by  ReactiveX Event  Bus  Libraries  for  Android //  this  is  the  middleman  object public class RxBus { private Subject<Object,  Object> bus  = new SerializedSubject<>(PublishSubject.create()); public void send(Object o)  { bus.onNext(o); } public Observable<Object> toObserverable()  { return bus; } } @OnClick(R.id.btn_demo_rxbus_tap) public void onTapButtonClicked()   { bus.send(new TapEvent()); } bus.toObserverable() .subscribe(new Action1<Object>()   { @Override public void call(Object event)   { if(event   instanceof TapEvent)   { _showTapText(); }else if(event   instanceof SomeOtherEvent)   { _doSomethingElse(); } } });
  • 27. References 1. https://github.com/square/otto-­intellij-­plugin 2. http://cases.azoft.com/message-­bus-­in-­android-­apps/ 3. http://poohdish.ghost.io/what-­is-­event-­bus/ 4. http://timnew.me/blog/2014/12/06/typical-­eventbus-­design-­patterns/ 5. https://github.com/greenrobot/EventBus/blob/master/COMPARISON.md 6. http://nerds.weddingpartyapp.com/tech/2014/12/24/implementing-­an-­event-­bus-­with-­rxjava-­rxbus/ 7. https://github.com/greenrobot/EventBus 8. https://github.com/kaushikgopal/RxJava-­Android-­ Samples/blob/master/app/src/main/java/com/morihacky/android/rxjava/rxbus