Skip to content

πŸ”” Feeds

Marc Rousavy edited this page Aug 20, 2018 · 11 revisions

The IFeed<T> interface declares a basic feed that can be used to notify any subscribers in this feed about sudden changes within the application domain in realtime. (Implementation: Feed<T>)

As this class is generic, you can use any type you want. Each type TMessage has it's own feed, so IFeed<string> and IFeed<int> will never interfere each other.

Subscribe

To subscribe to a feed, implement the INode<T> interface and call the Register() extension method:

class CustomViewModel : INode<NotifyReason>
{
    public CustomViewModel
    {
        this.Register();
    }

    public void MessageReceived(NotifyReason reason)
    { ... }
}

For each INode<T> a weak reference is maintained and removed if the INode<T> instance is garbage collected. You can manually unsubscribe aswell using the Unregister extension method.

If there are multiple feeds you want to subscribe to, you must explicitly declare the generic type on the Subscribe() call:

class CustomViewModel : INode<NotifyReason>, INode<NewUser>
{
    public CustomViewModel
    {
        this.Register<NotifyReason>();
        this.Register<NewUser>();
    }

    public void MessageReceived(NotifyReason reason)
    { ... }
    public void MessageReceived(NewUser newUser)
    { ... }
}

Please note that there are no polymorphic subscribers, so when notifying Feed<string>, the base type(s) (in this case Feed<object>) will not be notified.

Notify

To notify all subscribers, use the static Notify function:

Feed.Notify(NotifyReason.RefreshView);

The Feed<T> instance can also be accessed using the Feed<T>.Instance singleton property.



Example

For example, an application has two windows:

  • Users-List: A list of all registered users
  • Create-User: Allows creation of new user

Upon user creation, the user-list window has to be updated.

For this, a class containing the user-creation results needs to be defined:

class NewUser
{
    DateTime CreatedAt { get; }
    User User { get; }
}

Create-User Window:

Feed.Notify(new NewUser(DateTime.Now, createdUser));

User-List Window:

class UserListViewModel : INode<NewUser>
{
    void MessageReceived(NewUser newUser)
    {
        Users.Add(newUser.User);
    }
}

Result:

Demo Screenshot

Clone this wiki locally