我正在试图弄清楚如何将函数式编程应用于我在Android应用程序中编写的功能。阅读The introduction to Reactive Programming you've been missing,Retrofit and RxJava, Android multi-threaded REST requests和Why you should use RxJava in Android a short introduction to RxJava后,反应式编程似乎非常适合此功能。
情境:
要从REST API调用中获取值,有两个阶段:
由于我是反应式编程的新手,我想我应该从反编程风格编写伪代码开始。然后我必须将伪代码转换为适合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
问题: