C#返回变量可观察

时间:2019-11-25 10:41:04

标签: c# reactive unirx

我有将某些字符数据从外部db加载到内部db(infoBase)的方法,这些数据看起来像某种CharacterInfo对象列表。该方法返回observable。但是,如果用户尝试加载已经加载的字符数据,我希望直接从内部数据库将数据提供给用户。

    public IObservable<IEnumerable<CharacterInfo>> LoadCharactersOverviewAsync(CharacterInfoBase infoBase, params int[] char_id)
    {

        //Filter that search ids of characters that weren't load yet
        IEnumerable<int> char_id_filtered = ... ;    

        //If list is empty than it means that all we need is already loaded
        if (!char_id_filtered.Any())
          {
            //get list of necessary CharacterInfos from inner db
            IEnumerable<CharacterInfo> result = infoBase.Where(...);
            //Crunch. Don't know hot to return 1 collection as observable
            return Observable.FromCoroutineValue<IEnumerable<CharacterInfo>>(()=> Result(result));
          }
        ...

        //Returns observable result
        return JsonRequestExecutor.GetRequest(requestParameters)
            .Select(json =>
            {
                ...
            }
        );

    }

因此,如您所见,我将紧缩程序从协程中创建为可观察到的,只是为了返回结果

IEnumerator Result(IEnumerable<CharacterInfo> result)
    {
        yield return result;
    }

请告诉我,如何使其更好? 附言对不起,我的英语

1 个答案:

答案 0 :(得分:0)

我自己找到了答案。 在UniRX中没有可观察到的运算符。 http://reactivex.io/documentation/operators/just.html 但是有操作员开始 http://reactivex.io/documentation/operators/start.html

所以这是结果。也许这并不理想,但比我以前拥有的安静了

 if (!char_id_filtered.Any())
      {
        //get list of necessary CharacterInfos from inner db
        IEnumerable<CharacterInfo> result = infoBase.Where(...);
        //Here is the result
        return Observable.Start(() =>result);
      }