如何在Android屏幕上使用反应式编程来显示缓存的网络数据?

时间:2017-04-25 20:59:51

标签: functional-programming rx-java reactive-programming rx-android

我正在试图弄清楚如何将函数式编程应用于我在Android应用程序中编写的功能。阅读The introduction to Reactive Programming you've been missingRetrofit and RxJava, Android multi-threaded REST requestsWhy you should use RxJava in Android a short introduction to RxJava后,反应式编程似乎非常适合此功能。

情境:

  1. 用户点按设置
  2. 列表中填充了一组缓存(在磁盘上)来自REST API调用的值
  3. 用户可以通过单击刷新按钮
  4. 刷新缓存

    要从REST API调用中获取值,有两个阶段:

    1. API1 - 返回ids(需要两个HTTP请求标头,“日期”和“授权”进行身份验证)
    2. API2 - 给定一个id,返回有关该id的详细信息(无身份验证)
    3. 由于我是反应式编程的新手,我想我应该从反编程风格编写伪代码开始。然后我必须将伪代码转换为适合Android的实际Java代码。要做到这一点,我需要知道哪些是最适合我的任务的反应式编程库。

      要开始编写伪代码,我将使用The introduction to Reactive Programming you've been missing中的@andré-staltz语法:

      User_Actions:

      -i-----------i---------------> screen_initialization: user goes into screen
      -N-----------Y---------------> check_cache: map() gives N if data not found in db, Y otherwise
      -q---------------------------> do_refresh_cache1: filter() out anything by N
      ----------------r------------> refresh_button_clicks
      -q--------------r------------> do_refresh_cache2: merge() streams screen_initialization and do_refresh_cache1
      

      缓存:

      -q--------------r------------> clear_cache: map() do_refresh_cache2, clearing datBAase
      -cba|-----------cbad|--------> get_ids: flatMap() call API1 for ids (e.g. q results in 3 ids: a, b, c)
      -CBA|-----------CBAD|--------> get_details: map() calls API2 for each id to get details
      -CBA|-----------CBAD|--------> persist: map() persists each value (A, B, C, etc.) in the datBAase cache
      ----P---------------P--------> emit_ready: toPromise() emits a signal when we have details for each id
      

      装载

      -q--------------r------------> do_load_from_cache: merge() streams screen_initialization and do_refresh_cache1
      ----P---------------P--------> wait_for_ready: fromPromise() waits for a signal when we have details for each id
      ----CBA|------------CBAD|----> load_from_cache: flatMap() query database for id details when wait_for_ready promise fullfilled 
      -------ABC|-------------ABCD|> display: somehow sort the results
      

      UI:

      -s--------------s------------> show_spinner: map() do_refresh_cache2 to show a spinner while making network calls
      ----------h-----------------h> hide_spinner: hide spinner when display stream finishes
      

      问题:

      1. Psuedo-code:如何使我的伪代码符合要求?
      2. 真正的代码:RxJava,RxAndroid或其他一些反应式编程库中的哪些方法应该将伪代码转换为Android的实际代码?

0 个答案:

没有答案