查询Firebase值OnChange

时间:2016-09-13 18:05:31

标签: xamarin firebase xamarin.android firebase-realtime-database

我正在尝试注册一个Xamarin应用程序来监听特定值更改的值更改。我可以访问该值,但出于某种原因,当我听到值更改时,它将触发一次但不会再次触发,直到我重新启动。

我正在使用Xamarin Studio和FireSharp库。这是应用程序的C#库部分中的API代码。我删除委托的原因是检查在第一次通话后是否清理了代理人。

public class ValueAPI
{
    private IFirebaseClient _client;
    private ITemperatureListener _listener;
    private EventStreamResponse _response;

    public ValueAPI()
    {
        IFirebaseConfig config = new FirebaseConfig
        {
            AuthSecret = "...",
            BasePath = "https://[value-api].firebaseio.com/"
        };

        _client = new FirebaseClient(config);
    }

    public async Task<string> getValue()
    {
        FirebaseResponse response = await _client.GetAsync("VALUE");

        return response.Body;
    }

    public async Task<string> registerForUpdates(IValueListener listener)
    {
        _listener = listener;
        _response = await _client.OnAsync("VALUE", null,  this.OnValueChange, null, null);

        return _response.ToString();
    }

    private void OnValueChange(object sender, ValueChangedEventArgs args, object context)
    {
        if (_listener != null)
        {
            _listener.OnValueUpdated(args.Data);
        }
    }
}

ANDROID CODE

ValueAPI api = new ValueAPI();

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);   

    getValue();
    getValueUpdates();
}

private async void getValue()
{
    Task<string> task = api.getValue();
    string result = await task;

    TextView label = (TextView)FindViewById(Resource.Id.label_value);
    label.Text = result;
}

private async void getValueUpdates()
{
    Task<string> task = api.registerForUpdates(this);
    await task;
}

public void OnValueUpdated(string value)
{
    TextView label = (TextView)FindViewById(Resource.Id.label_value_updated);
    label.Text = value;
}

0 个答案:

没有答案