将observable插入另一个observable

时间:2016-11-07 14:35:01

标签: c# xamarin xamarin.android system.reactive

假设[伪]代码:

class MyActivity : Activity {

   Observable<string> mainObl

   void OnCreate(Bundle bundle) {
      mainObl = Observable.Never<string>();
   }


   Disposable subscription;

   void OnStart() {
      subscription = mainObl.Subscribe(UpdateUiOnEvent);
   }

   void OnStop() {
      subscription.Dispose();
   }


   // on click - start filling existing Observable with data from another source
   void OnButtonClick() {
      var tmpObl = Observale.just(1,2,3,4);
      mainObl.WhatMethodHere(tmpObl); // <<<<<<<<<<<< see Q
   }

}

Ad Q:
在上面WhatMethodHere中使用哪种方法来挂钩mainOble中的tmpObl 或者如何从另一个源[另一个可观察的]开始注入现有的Observable数据?

=== update ===
警告:提出的问题是Rx Android中的不良做法

我问这是RX用户的开始 但回答正确回答最初的问题

2 个答案:

答案 0 :(得分:3)

执行此操作的最佳方法是将所有内容保留在Observable空间中,而不是尝试混合事件和可观察代码。假设您的按钮名为“button1”,您可以使用以下[伪]代码实现此目的:

class MyActivity : Activity {

   IDisposable subscription;

   void OnStart() {
      subscription = Observable
          // Adapt a delegate to the event signature and subscribe to the event (unsubscribing when subscription disposed)
          .FromEventPattern<EventHandler,EventArgs>(handler => (s,e) => handler(e), handler => button1.TouchUpInside += handler, handler => button1.TouchUpInside -= handler)               
          // Emit a new observable containing the data "from another source"
          .Select(args => Observable.Return("1", "2", "3", "4"))
          // Dispose any subscription to the previous observable and subscribe to the new observable emitted from above           
          .Switch()
          .Subscribe(UpdateUiOnEvent);
   }

   void OnStop() {
      subscription.Dispose();
   }
}

希望它有所帮助。

答案 1 :(得分:0)

如果我试图将代码保持在与现在相同的结构中,我会做这样的事情:

class MyActivity
{
    private Subject<IObservable<string>> mainObl;
    private IDisposable subscription = null;

    public void OnCreate()
    {
        mainObl = new Subject<IObservable<string>>();
    }

    public void OnStart()
    {
        subscription = mainObl.Merge().Subscribe(x =>
        {
            Console.WriteLine(x);
        });
    }

    public void OnStop()
    {
        subscription.Dispose();
    }

    public void OnButtonClick()
    {
        var tmpObl = new [] { 1, 2, 3, 4 }
            .Select(x => x.ToString())
            .ToObservable();
        mainObl.OnNext(tmpObl);
    }
}

现在你打电话给我:

var ma = new MyActivity();

ma.OnCreate();
ma.OnStart();
ma.OnButtonClick();

...你明白了:

1
2
3
4