Search code examples
c#redissystem.reactiveobservableredisclient

use publish/subscribe with sider redis C# client


I am using Sider C# Redis client to connect to Redis server running on my windows 7 machine. https://github.com/chakrit/sider

I am able to fire set/get/select from my C# application

I now want to use the Publish/Subscribe feature so that my C# app can be informed about any changes in the redis client's "key" in an evented way (passing delegates)

I am unable to write the code for that as there are no examples on how to use the sider client page.

all i could write was this :

var client = new RedisClient(address, 6379);
string[] keys = new string[1];
keys[0] = "key1ToMonitor";
IObservable<Message<string>> obb = client.Subscribe(keys);

I know this looks lame but i got no clue how to write it in an lambda way where my function would be called if any client changes the desired keys on the redis server.

PS : I am new to this so correct me if my approach is flawed.

Edit : on adding the suggested changes i am getting the following error.

Error   7   Cannot convert lambda expression to type 'System.IObserver<Sider.Message<string>>' because it is not a delegate type    D:\_Work\TestApp\Program.cs 90  27  TestApp

the obb.subscribe signature looks like this

namespace System
{
    // Summary:
    //     Defines a provider for push-based notification.
    //
    // Type parameters:
    //   T:
    //     The object that provides notification information.This type parameter is
    //     covariant. That is, you can use either the type you specified or any type
    //     that is more derived. For more information about covariance and contravariance,
    //     see Covariance and Contravariance in Generics.
    public interface IObservable<out T>
    {
        // Summary:
        //     Notifies the provider that an observer is to receive notifications.
        //
        // Parameters:
        //   observer:
        //     The object that is to receive notifications.
        //
        // Returns:
        //     The observer's interface that enables resources to be disposed.
        IDisposable Subscribe(IObserver<T> observer);
    }
}

code :

        var client = new RedisClient(address, 6379);
        string[] keys = new string[1];
        keys[0] = "key1ToMonitor";
        IObservable<Message<string>> obb = client.Subscribe(keys);
        obb.Subscribe(x => Debug.WriteLine(x.ToString()) ); // error : doesn't let me compile  

Solution

  • You need to subscribe to the actual observable produced. Something like this:

    obb.Subscribe(x => Debug.WriteLine(x.ToString()));
    

    Don't forget to add using System.Reactive.Linq; to get the extensions required to convert a lambda into an observer.