Skip to content

πŸ”” Feeds

Marc Rousavy edited this page Aug 23, 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 Subscribe() extension method:

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

    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 Unsubscribe() 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.Subscribe<NotifyReason>();
        this.Subscribe<NewUser>();
    }

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

There is no polymorphism when notifying feeds, so when notifying Feed<string>, the base type(s) (in this case Feed<object>) will not be notified. You can explicitly notify base feeds by specifying the generic type: Feed.Notify<object>("string notification")

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