Search Results

Search found 237 results on 10 pages for 'observer'.

Page 3/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Object Events, how do are they implemented

    - by Malfist
    Events are really awesome, and I wouldn't know what I would do without them, but they're a mystery to me. I'm talking about events in a sense, a function(s) is called if a property, or value, a special event happens. I have only the vaguest idea how these actually work. I know it's an observer pattern, but I don't truly know how it works and/or how to implement it. Can someone explain that to me?

    Read the article

  • Key Coder/Observer example for Iphone

    - by ReduxDJ
    I'm trying to implement KVO into an application, yet, I've followed the documentation provided by Apple, however I can't get it to work. I'm hoping to see a bare minimal example of how to use this with my NSObjects. My use case, is I want one item in a table-cell to update without loading the entire data in a tableView because I am loading images from URLs and I don't want to reload all of the image, while I am polling a server. Thanks,

    Read the article

  • Observer pattern and violation of Single Principality Rule

    - by Devil Jin
    I have an applet which repaints itself once the text has changed Design 1: //MyApplet.java public class MyApplet extends Applet implements Listener{ private DynamicText text = null; public void init(){ text = new DynamicText("Welcome"); } public void paint(Graphics g){ g.drawString(text.getText(), 50, 30); } //implement Listener update() method public void update(){ repaint(); } } //DynamicText.java public class DynamicText implements Publisher{ // implements Publisher interface methods //notify listeners whenever text changes } Isn't this a violation of Single Responsibility Principle where my Applet not only acts as Applet but also has to do Listener job. Same way DynamicText class not only generates the dynamic text but updates the registered listeners. Design 2: //MyApplet.java public class MyApplet extends Applet{ private AppletListener appLstnr = null; public void init(){ appLstnr = new AppletListener(this); // applet stuff } } // AppletListener.java public class AppletListener implements Listener{ private Applet applet = null; public AppletListener(Applet applet){ this.applet = applet; } public void update(){ this.applet.repaint(); } } // DynamicText public class DynamicText{ private TextPublisher textPblshr = null; public DynamicText(TextPublisher txtPblshr){ this.textPblshr = txtPblshr; } // call textPblshr.notifyListeners whenever text changes } public class TextPublisher implments Publisher{ // implements publisher interface methods } Q1. Is design 1 a SPR violation? Q2. Is composition a better choice here to remove SPR violation as in design 2.

    Read the article

  • How to observer when a UIAlertView is displayed?

    - by DotSlashSlash
    Is it anyway possible to observe if a UIAlertView is being displayed and call a function when it is. The UIAlertView is not being created and displayed in the same class which I want a function to be called in. Its hard to explain but to put it simply I need to somehow monitor or observe if the view becomes like out of first responder or something because I dont think it is possible to monitor if a UIAlertView is being displayed :/

    Read the article

  • Class as an Event Observer

    - by emi
    I want to do something like this... var Color = Class.create({ initialize: function() { this._color = "white"; this.observe("evt: colorChanged", this.colorChanged.bind(this)); }, changeColor: function(color) { this._color = color; this.fire("evt: colorChanged"); }, colorChanged: function(event) { alert("You change my color!"); } }); var a = new Color().changeColor("blue"); Why the colorChange custom event will never be dispatched and I need to use, instead of this, a DOM element like document.observe? In my code I'd like to know which class dispatches the event using event.target and I can't if I must use document or some other DOM element. :( I've been working in Actionscript 3 and that's the methodology I learned to work with custom events in classes. What about Javascript?

    Read the article

  • File observer problem

    - by Nemat
    Hi, I want to listen to the changes occured in file system.I am using FileObserver.Here is my code: Code: class MyDirObserver extends FileObserver { String superPath; public MyDirObserver(String path) { super(path, ALL_EVENTS); this.superPath=path; } public void onEvent(int event, String path) { Log.e("onEvent of Directory", "=== onEvent ==="); try{ _Dump("dir", event, path,superPath); } catch(NullPointerException ex) { Log.e("ERROR","I am getting error"); } } } private void _Dump(final String tag, int event, String path,String superPath) { Log.d(tag, "=== dump begin ==="); Log.d(tag, "path=" + path); Log.d(tag,"super path="+superPath); Log.d(tag, "event list:"); if ((event & FileObserver.OPEN) != 0) { Log.d(tag, " OPEN"); } if ((event & FileObserver.CLOSE_NOWRITE) != 0) { Log.d(tag, " CLOSE_NOWRITE"); } if ((event & FileObserver.CLOSE_WRITE) != 0) { Log.d(tag, " CLOSE_WRITE"); Log.i("NEWFILEOBSERVER","File is Modified"); if(path!=null) { Log.d("---------FilePath",superPath+path); } } if ((event & FileObserver.CREATE) != 0) { isCreate=true; Log.i("NEWFILEOBSERVER","File is Created "); if(path!=null) { Log.d("---------FilePath",superPath+path); } Log.d(tag, " CREATE"); } if ((event & FileObserver.DELETE) != 0) { Log.i("NEWFILEOBSERVER","File is deleted"); if(path!=null) { Log.d("---------FilePath",superPath+path); } // startMyActivity("A new file is deleted thats="+superPath); Log.d(tag, " DELETE"); } if ((event & FileObserver.DELETE_SELF) != 0) { Log.d(tag, " DELETE_SELF"); } if ((event & FileObserver.ACCESS) != 0) { Log.d(tag, " ACCESS"); } if ((event & FileObserver.MODIFY) != 0) { if(!isModified) isModified=true; if(isModified && isOpen) isAgainModified=true; Log.d(tag, " MODIFY"); } if ((event & FileObserver.MOVED_FROM) != 0) { Log.d(tag, " MOVED_FROM"); if(path!=null) { Log.d("---------FilePath",superPath+path); } } if ((event & FileObserver.MOVED_TO) != 0) { Log.d(tag, " MOVED_TO"); if(path!=null) { Log.d("---------FilePath",superPath+path); } } if ((event & FileObserver.MOVE_SELF) != 0) { Log.d(tag, " MOVE_SELF"); } if ((event & FileObserver.ATTRIB) != 0) { Log.d(tag, " ATTRIB"); } Log.d(tag, "=== dump end ==="); } it stops after some time.I dont get the exact time but doesnt work always though I call startWatching() in service in a loop which runs for all the folders of sdcard and calls startWatching() for each of them. It shows unpredictable behaviour and stops listening for some folders and runs perfectly for the others. I hope you guys help me.I tried many ways but it doesnt work perfectly.Am I doing something wrong??? or there we have some other way to do this....... Please help me........I have to get this done withing few days...... Any help is appreciated!!!! Thanks in Advance Nemat

    Read the article

  • Observer pattern and violation of Single Responsibility Principle

    - by Devil Jin
    I have an applet which repaints itself once the text has changed Design 1: //MyApplet.java public class MyApplet extends Applet implements Listener{ private DynamicText text = null; public void init(){ text = new DynamicText("Welcome"); } public void paint(Graphics g){ g.drawString(text.getText(), 50, 30); } //implement Listener update() method public void update(){ repaint(); } } //DynamicText.java public class DynamicText implements Publisher{ // implements Publisher interface methods //notify listeners whenever text changes } Isn't this a violation of Single Responsibility Principle where my Applet not only acts as Applet but also has to do Listener job. Same way DynamicText class not only generates the dynamic text but updates the registered listeners. Design 2: //MyApplet.java public class MyApplet extends Applet{ private AppletListener appLstnr = null; public void init(){ appLstnr = new AppletListener(this); // applet stuff } } // AppletListener.java public class AppletListener implements Listener{ private Applet applet = null; public AppletListener(Applet applet){ this.applet = applet; } public void update(){ this.applet.repaint(); } } // DynamicText public class DynamicText{ private TextPublisher textPblshr = null; public DynamicText(TextPublisher txtPblshr){ this.textPblshr = txtPblshr; } // call textPblshr.notifyListeners whenever text changes } public class TextPublisher implments Publisher{ // implements publisher interface methods } Q1. Is design 1 a SPR violation? Q2. Is composition a better choice here to remove SPR violation as in design 2.

    Read the article

  • Can i create different observables and different corresponding observers in java?

    - by mithun1538
    Hello everyone, Currently, I have one observable and many observers. What i need is different observables, and depending on the observable, different observers. How do I achieve this? ( For understanding, assume I have different apples - say apple1 apple2... I have observer_1 observing apple1, observer_2 observing apple2, observer_3 observing apple 2 and so on..). I tried creating different objects of the Observable class, but since observers are observing the same class of observable, I don't know how to access a particular instance of the Observable. I have included the following servlet code that contains Observer and Observable classes: public class CustomerServlet extends HttpServlet { public String getNextMessage() { // Create a message sink to wait for a new message from the // message source. return new MessageSink().getNextMessage(source); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ObjectOutputStream dout = new ObjectOutputStream(response.getOutputStream()); String recMSG = getNextMessage(); dout.writeObject(recMSG); dout.flush(); } public void broadcastMessage(String message) { // Send the message to all the HTTP-connected clients by giving the // message to the message source source.sendMessage(message); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ObjectInputStream din= new ObjectInputStream(request.getInputStream()); String message = (String)din.readObject(); ObjectOutputStream dout = new ObjectOutputStream(response.getOutputStream()); dout.writeObject("1"); dout.flush(); if (message != null) { broadcastMessage(message); } // Set the status code to indicate there will be no response response.setStatus(response.SC_NO_CONTENT); } catch (Exception e) { e.printStackTrace(); } } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> MessageSource source = new MessageSource(); } class MessageSource extends Observable { public void sendMessage(String message) { setChanged(); notifyObservers(message); } } class MessageSource extends Observable { public void sendMessage(String message) { setChanged(); notifyObservers(message); } } class MessageSink implements Observer { String message = null; // set by update() and read by getNextMessage() // Called by the message source when it gets a new message synchronized public void update(Observable o, Object arg) { // Get the new message message = (String)arg; // Wake up our waiting thread notify(); } // Gets the next message sent out from the message source synchronized public String getNextMessage(MessageSource source) { // Tell source we want to be told about new messages source.addObserver(this); // Wait until our update() method receives a message while (message == null) { try { wait(); } catch (Exception e) { System.out.println("Exception has occured! ERR ERR ERR"); } } // Tell source to stop telling us about new messages source.deleteObserver(this); // Now return the message we received // But first set the message instance variable to null // so update() and getNextMessage() can be called again. String messageCopy = message; message = null; return messageCopy; } }

    Read the article

  • Resolve php "deadlock"

    - by Matt
    Hey all, I'm currently running into a situation that I guess would be called deadlock. I'm implementing a message service that calls various object methods.. it's quite similar to observer pattern.. Here's whats going on: Dispatcher.php Dispatcher.php <? class Dispatcher { ... public function message($name, $method) { // Find the object based on the name $object = $this->findObjectByName($name); // Slight psuedocode.. for ease of example if($this->not_initialized($object)) $object = new $object(); // This is where it locks up. } return $object->$method(); ... } class A { function __construct() { $Dispatcher->message("B", "getName"); } public function getName() { return "Class A"; } } class B { function __construct() { // Assume $Dispatcher is the classes $Dispatcher->message("A", "getName"); } public function getName() { return "Class B"; } } ?> It locks up when neither object is initialized. It just goes back and forth from message each other and no one can be initialized. Any help would be immensely helpful.. Thanks! Matt Mueller

    Read the article

  • Resolve php endless recursion issue

    - by Matt
    Hey all, I'm currently running into an endless recursion situation. I'm implementing a message service that calls various object methods.. it's quite similar to observer pattern.. Here's whats going on: Dispatcher.php class Dispatcher { ... public function message($name, $method) { // Find the object based on the name $object = $this->findObjectByName($name); // Slight psuedocode.. for ease of example if($this->not_initialized($object)) $object = new $object(); // This is where it locks up. } return $object->$method(); ... } class A { function __construct() { $Dispatcher->message("B", "getName"); } public function getName() { return "Class A"; } } class B { function __construct() { // Assume $Dispatcher is the classes $Dispatcher->message("A", "getName"); } public function getName() { return "Class B"; } } It locks up when neither object is initialized. It just goes back and forth from message each other and no one can be initialized. I'm looking for some kind of queue implementation that will make messages wait for each other.. One where the return values still get set. I'm looking to have as little boilerplate code in class A and class B as possible Any help would be immensely helpful.. Thanks! Matt Mueller

    Read the article

  • Simple Observation in Django: How Can I Correctly Modify The `attrs` sent to __new__ of a Django Mod

    - by DGGenuine
    Hello, I'm a strong proponent of the observer pattern, and this is what I'd like to be able to do in my Django models.py: class AModel(Model): __metaclass__ = SomethingMagical @post_save(AnotherModel) @classmethod def observe_another_model_saved(klass, sender, instance, created, **kwargs): pass @pre_init('YetAnotherModel') @classmethod def observe_yet_another_model_initializing(klass, sender, *args, **kwargs): pass @post_delete('DifferentApp.SomeModel') @classmethod def observe_some_model_deleted(klass, sender, **kwargs): pass This would connect a signal with sender = the decorator's argument and receiver = the decorated method. Right now my signal connection code all exists in __init__.py which is okay, but a little unmaintainable. I want this code all in one place, the models.py file. Thanks to helpful feedback from the community I'm very close (I think.) (I'm using a metaclass solution instead of the class decorator solution in the previous question/answer because you can't set attributes on classmethods, which I need.) I am having a strange error I don't understand. At the end of my post are the contents of a models.py that you can pop into a fresh project/application to see the error. Set your database to sqlite and add the application to installed apps. This is the error: Validating models... Unhandled exception in thread started by Traceback (most recent call last): File "/Library/Python/2.6/site-packages//lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 253, in validate raise CommandError("One or more models did not validate:\n%s" % error_text) django.core.management.base.CommandError: One or more models did not validate: local.myothermodel: 'my_model' has a relation with model MyModel, which has either not been installed or is abstract. I've indicated a few different things you can comment in/out to fix the error. First, if you don't modify the attrs sent to the metaclass's __new__, then the error does not arise. (Note even if you copy the dictionary element by element into a new dictionary, it still fails; only using the exact attrs dictionary works.) Second, if you reference the first model by class rather than by string, the error also doesn't arise regardless of what you do in __new__. I appreciate your help. I'll be githubbing the solution if and when it works. Maybe other people would enjoy a simplified way to use Django signals to observe application happenings. #models.py from django.db import models from django.db.models.base import ModelBase from django.db.models import signals import pdb class UnconnectedMethodWrapper(object): sender = None method = None signal = None def __init__(self, signal, sender, method): self.signal = signal self.sender = sender self.method = method def post_save(sender): return _make_decorator(signals.post_save, sender) def _make_decorator(signal, sender): def decorator(view): return UnconnectedMethodWrapper(signal, sender, view) return decorator class ConnectableModel(ModelBase): """ A meta class for any class that will have static or class methods that need to be connected to signals. """ def __new__(cls, name, bases, attrs): unconnecteds = {} ## NO WORK newattrs = {} for name, attr in attrs.iteritems(): if isinstance(attr, UnconnectedMethodWrapper): unconnecteds[name] = attr newattrs[name] = attr.method #replace the UnconnectedMethodWrapper with the method it wrapped. else: newattrs[name] = attr ## NO WORK # newattrs = {} # for name, attr in attrs.iteritems(): # newattrs[name] = attr ## WORKS # newattrs = attrs new = super(ConnectableModel, cls).__new__(cls, name, bases, newattrs) for name, unconnected in unconnecteds.iteritems(): _connect_signal(unconnected.signal, unconnected.sender, getattr(new, name), new._meta.app_label) return new def _connect_signal(signal, sender, receiver, default_app_label): # full implementation also accepts basestring as sender and will look up model accordingly signal.connect(sender=sender, receiver=receiver) class MyModel(models.Model): __metaclass__ = ConnectableModel @post_save('In my application this string matters') @classmethod def observe_it(klass, sender, instance, created, **kwargs): pass @classmethod def normal_class_method(klass): pass class MyOtherModel(models.Model): ## WORKS # my_model = models.ForeignKey(MyModel) ## NO WORK my_model = models.ForeignKey('MyModel')

    Read the article

  • GDB says that a KVO observer is registered even though it is not (or is it?).

    - by Paperflyer
    When my application is closed, the main controller class removes itself as Observer from the model and then releases the model. Like this: - (void)dealloc { [theModel removeObserver:self forKeyPath:@"myValue"]; [theModel release]; [super dealloc]; } And right after that, the debugger says: 2010-04-29 14:07:40.294 MyProgram[13678:a0f] An instance 0x116f2e880 of class TheModel was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info: <NSKeyValueObservationInfo 0x100288450> ( <NSKeyValueObservance 0x1002aca90: Observer: 0x116f40ec0, Key path: myValue, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x116f80430> ) where 0x116f2e880 is indeed the model and 0x116f40ec0 is indeed the controller. How can the controller still be an observer when it just removed itself as an observer?

    Read the article

  • How can I update information in an Android Activity from a background Service

    - by tmm
    Hello, I am trying to create a simple Android application that has a ActivityList of information, when the application starts, I plan to start a Service that will be constantly calculating the data (it will be changing) and I want the ActivityList to be in sync with the data that the service is calculating for the life of the app. How can I set up my Activity to be listening to the Service? Is this the best way to approach this problem? For example, if you imagine a list of stock prices - the data would be being changed regularly and need to be in sync with the (in my case) Service that is calculating/fetching the data constantly. Thanks in advance

    Read the article

  • JBoss Seam - order event listeners

    - by Walter White
    Hi all, I would like to order my event listeners. Is it possible to do this in JBoss Seam 2.x? I am thinking as a workaround, which is quite simple, I will just daisy chain my events: fire event A. do something on event A. a. fire event B do something on event B. Any comments with this design? Is this a good / bad practice? Thanks, Walter

    Read the article

  • Reg : Contact changes in Android

    - by Laxman
    Hi, I am using ContentObserver on contacts. But here my problem is atleast once i have to launch my application other wise i am unable to get notification chages. My code like this ContactsContentObserver cco = new ContactsContentObserver(handler); ContentResolver contentResolver = getContentResolver(); contentResolver.registerContentObserver(RawContacts.CONTENT_URI, true, cco); } private class ContactsContentObserver extends ContentObserver { public ContactsContentObserver(Handler h) { super(h); } public void onChange(boolean selfChange) { System.out.println("##########SOMEBODAY CHANGED ANYTHING AT THE CONTACTS"); Toast.makeText(getApplication(),"####Updated####",Toast.LENGTH_LONG).show(); } .... Adv thanks. u can contact on [email protected]

    Read the article

  • Rails Cache Sweeper and Model Callback Firing

    - by Topher Fangio
    Hey guys, I have the following classes: class Vigil < ActiveRecord::Base after_update :do_something_cool private def do_something_cool # Sweet code here end end class NewsFeedObserver < ActionController::Caching::Sweeper observe Vigil def after_update # Create a news feed entry end end Everything works as expected. The after_update in the sweeper requires that the do_something_cool method in the model has finished before it can run properly. The problem is that the after_update in the sweeper is being called before (or perhaps at the same time as) the do_something_cool callback and it's causing problems. Does anyone know how to force the after_update in the sweeper to fire after the model callback? Is there better way to achieve this?

    Read the article

  • In Rails, a Sweeper isn't getting called in a Model-only setup

    - by charliepark
    I'm working on a Rails app, where I'm using page caching to store static html output. The caching works fine. I'm having trouble expiring the caches, though. I believe my problem is, in part, because I'm not expiring the cache from my controller. All of the actions necessary for this are being handled within the model. This seems like it should be doable, but all of the references to Model-based cache expiration that I'm finding seem to be out of date, or are otherwise not working. In my environment.rb file, I'm calling config.load_paths += %W( #{RAILS_ROOT}/app/sweepers ) And I have, in the /sweepers folder, a LinkSweeper file: class LinkSweeper < ActionController::Caching::Sweeper observe Link def after_update(link) clear_links_cache(link) end def clear_links_cache(link) # expire_page :controller => 'links', :action => 'show', :md5 => link.md5 expire_page '/l/'+ link.md5 + '.html' end end So ... why isn't it deleting the cached page when I update the model? (Process: using script/console, I'm selecting items from the database and saving them, but their corresponding pages aren't deleting from the cache), and I'm also calling the specific method in the Link model that would normally invoke the sweeper. Neither works. If it matters, the cached file is an md5 hash off a key value in the Links table. The cached page is getting stored as something like /l/45ed4aade64d427...99919cba2bd90f.html. Essentially, it seems as though the Sweeper isn't actually observing the Link. I also read (here) that it might be possible to simply add the sweeper to config.active_record.observers in environment.rb, but that didn't seem to do it (and I wasn't sure if the load_path of app/sweepers in environment.rb obviated that).

    Read the article

  • Can observer pattern be represented by cars and traffic lights?

    - by eeerahul
    I wanted to verify with all of you, if I have a correct Observer Pattern analogy. The scenario is as follows: Consider, at a junction, there is a traffic signal, having red, yellow and green lights respectively. There are vehicles facing the traffic signal post. When it shows red, the vehicles stop, when it shows green, the vehicles move on. In case, it is yellow, the driver must decide whether to go or to stop, depending on whether he/she has crossed the stop line or not. At the same time, there are vehicles that do not care about the signal. They would do as they like. The similarities are that, the Traffic Signal happens to be the subject, notifying its states by glowing the appropriate lights. Those looking at it and following the signal are the ones subscribed to it, and behave according to the state of the subject. Those who do not care about it, are sort-of un-subscribed from the traffic signal. Please tell me, if you think this is a correct analogy or not?

    Read the article

  • What's a good place to unregister an observer from the notification center?

    - by mystify
    When I add an observer to the default notification center, where would I unregister that? Example: I have a UIView subclass which lives inside a view controller. That subclass is an observer for the FooBarNotification. If this notification is posted, that view will get it. But now, the view controller decides to throw away the view. Is the best place the -dealloc method of the view itself? Are there any rules like memory management rules? For example: Must I unregister an observer where I registered it? i.e. the view registers itself in it's init method, so it should unregister itself in it's -dealloc method? (not talking about push notifications, but NSNotificationCenter)

    Read the article

  • Curious about IObservable? Here’s a quick example to get you started!

    - by Roman Schindlauer
    Have you heard about IObservable/IObserver support in Microsoft StreamInsight 1.1? Then you probably want to try it out. If this is your first incursion into the IObservable/IObserver pattern, this blog post is for you! StreamInsight 1.1 introduced the ability to use IEnumerable and IObservable objects as event sources and sinks. The IEnumerable case is pretty straightforward, since many data collections are already surfacing as this type. This was already covered by Colin in his blog. Creating your own IObservable event source is a little more involved but no less exciting – here is a primer: First, let’s look at a very simple Observable data source. All it does is publish an integer in regular time periods to its registered observers. (For more information on IObservable, see http://msdn.microsoft.com/en-us/library/dd990377.aspx ). sealed class RandomSubject : IObservable<int>, IDisposable {     private bool _done;     private readonly List<IObserver<int>> _observers;     private readonly Random _random;     private readonly object _sync;     private readonly Timer _timer;     private readonly int _timerPeriod;       /// <summary>     /// Random observable subject. It produces an integer in regular time periods.     /// </summary>     /// <param name="timerPeriod">Timer period (in milliseconds)</param>     public RandomSubject(int timerPeriod)     {         _done = false;         _observers = new List<IObserver<int>>();         _random = new Random();         _sync = new object();         _timer = new Timer(EmitRandomValue);         _timerPeriod = timerPeriod;         Schedule();     }       public IDisposable Subscribe(IObserver<int> observer)     {         lock (_sync)         {             _observers.Add(observer);         }         return new Subscription(this, observer);     }       public void OnNext(int value)     {         lock (_sync)         {             if (!_done)             {                 foreach (var observer in _observers)                 {                     observer.OnNext(value);                 }             }         }     }       public void OnError(Exception e)     {         lock (_sync)         {             foreach (var observer in _observers)             {                 observer.OnError(e);             }             _done = true;         }     }       public void OnCompleted()     {         lock (_sync)         {             foreach (var observer in _observers)             {                 observer.OnCompleted();             }             _done = true;         }     }       void IDisposable.Dispose()     {         _timer.Dispose();     }       private void Schedule()     {         lock (_sync)         {             if (!_done)             {                 _timer.Change(_timerPeriod, Timeout.Infinite);             }         }     }       private void EmitRandomValue(object _)     {         var value = (int)(_random.NextDouble() * 100);         Console.WriteLine("[Observable]\t" + value);         OnNext(value);         Schedule();     }       private sealed class Subscription : IDisposable     {         private readonly RandomSubject _subject;         private IObserver<int> _observer;           public Subscription(RandomSubject subject, IObserver<int> observer)         {             _subject = subject;             _observer = observer;         }           public void Dispose()         {             IObserver<int> observer = _observer;             if (null != observer)             {                 lock (_subject._sync)                 {                     _subject._observers.Remove(observer);                 }                 _observer = null;             }         }     } }   So far, so good. Now let’s write a program that consumes data emitted by the observable as a stream of point events in a Streaminsight query. First, let’s define our payload type: class Payload {     public int Value { get; set; }       public override string ToString()     {         return "[StreamInsight]\tValue: " + Value.ToString();     } }   Now, let’s write the program. First, we will instantiate the observable subject. Then we’ll use the ToPointStream() method to consume it as a stream. We can now write any query over the source - here, a simple pass-through query. class Program {     static void Main(string[] args)     {         Console.WriteLine("Starting observable source...");         using (var source = new RandomSubject(500))         {             Console.WriteLine("Started observable source.");             using (var server = Server.Create("Default"))             {                 var application = server.CreateApplication("My Application");                   var stream = source.ToPointStream(application,                     e => PointEvent.CreateInsert(DateTime.Now, new Payload { Value = e }),                     AdvanceTimeSettings.StrictlyIncreasingStartTime,                     "Observable Stream");                   var query = from e in stream                             select e;                   [...]   We’re done with consuming input and querying it! But you probably want to see the output of the query. Did you know you can turn a query into an observable subject as well? Let’s do precisely that, and exploit the Reactive Extensions for .NET (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to quickly visualize the output. Notice we’re subscribing “Console.WriteLine()” to the query, a pattern you may find useful for quick debugging of your queries. Reminder: you’ll need to install the Reactive Extensions for .NET (Rx for .NET Framework 4.0), and reference System.CoreEx and System.Reactive in your project.                 [...]                   Console.ReadLine();                 Console.WriteLine("Starting query...");                 using (query.ToObservable().Subscribe(Console.WriteLine))                 {                     Console.WriteLine("Started query.");                     Console.ReadLine();                     Console.WriteLine("Stopping query...");                 }                 Console.WriteLine("Stopped query.");             }             Console.ReadLine();             Console.WriteLine("Stopping observable source...");             source.OnCompleted();         }         Console.WriteLine("Stopped observable source.");     } }   We hope this blog post gets you started. And for bonus points, you can go ahead and rewrite the observable source (the RandomSubject class) using the Reactive Extensions for .NET! The entire sample project is attached to this article. Happy querying! Regards, The StreamInsight Team

    Read the article

  • How to remove an observer for NSNotification in a UIView?

    - by sudo rm -rf
    Hello! I've added an observer in a custom UIView I've created under initWithFrame:. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateZipFromLocation:) name:@"zipFoundFromLocation" object:nil]; The problem is, this view is a subview. When the view is loaded again, it calls the initWithFrame message again, thus adding two observers and so on. How can I remove the observer when the view is going to disappear? Since it is a UIView, it says that viewWillDisappear:(BOOL)animated is not a valid method. Any ideas?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >