什么時候不適合使用Rxjava

原文:http://tomstechnicalblog.blogspot.hk/2016/07/when-not-to-use-rxjava.html
中文:http://blog.chengyunfeng.com/?p=1009

When Not to Use RxJava

Reactive programming is a game-changing technology. If you are using it correctly, it should change how you approach programming entirely. Over a year ago, I researched it hoping to find a better way to manage and compose UI events (and consequently took ownership of RxJavaFX). But I quickly learned it accomplishes muchmore than that. It changes the approach to almost every aspect of programming, from concurrency and IO to logic and algorithms.

In my enthusiasm, I started using RxJava for pretty much everything. Taking this ground-up approach to reactive programming greatly benefited the quality of my applications. For me, making everything reactive was probably the most effective way to learn RxJava too.

But after a year, I did find a few cases where reactive may not necessarily be a good fit. Every application I write now will be reactive. However, there may be a few places in the codebase I strategically choose to not make reactive. This might have partially been due to my switch to Kotlin, which made functional programming convenient whether it is push-based or pull-based, making Rx only one of several functional tools in my belt. But I digress. This article is merely my observations when using an RxJava Observable might not be optimal.

Keep in mind it is easy to turn pretty much anything into an Observable, including collections. Therefore, this post is about when it is appropriate to allow non-Observable items to be returned from your API. The clients of the API can always turn these items into Observables if they choose.

Case #1 Small, Constant, and Unchanging Data Sets

Here is the simplest case where an Observable might not be appropriate. Let's say you have a simple enum type for three EmployeeType categories.

public enum EmployeeType {
    FULL_TIME,
    CONTRACTOR,
    INTERN
}

If you need to iterate through this enumerable, does it always make sense to turn it into an Observable for the sake of?

Observable<EmployeeType> employeeTypes = Observable.from(Employee.values());

Perhaps it might make sense to turn EmployeeType into an Observable if you are already deep in an Observable chain of operators, and it simply follows the push-based flow to turn it into an Observable. But I would argue this is the exception rather than the norm.

Data sets that are small and do not change are probably not good candidates to turn into an Observable. From an API perspective, leave it as a traditional collection and allow it to be converted to an Observable when it makes sense. This does not apply to just enumerables, and perhaps this was an extreme example. But any small, static data set could fall into this case.

Case #2 Expensive, Cached Objects

Let's say you have a class called ActionQualifier which has some expensive regular expression fields. In case you didn't know, regular expressions are text wildcards on steroids. They are very powerful in finding text patterns but they are very expensive to compile at runtime. So creating an instance of this ActionQualifier could be very costly on performance if done redundantly.

public final class ActionQualifier {

    private final Pattern codeRegexPattern;
    private final int actionNumber;

    ActionQualifier(String codeRegex, int actionNumber) {
        this.codeRegexPattern = Pattern.compile(codeRegex);
        this.actionNumber = actionNumber;
    }

    public boolean qualify(String code) {
        return codeRegexPattern.matcher(code).find();
    }
    public int getActionCode() {
        return actionNumber;
    }
}

If you had an Observable that imported ActionQualifier instances from a database using RxJava-JDBC, it could be very expensive if it has several subscribers (since every subscription results in a re-query). For every subscription, it would rebuild ALL of them each time.

Observable<ActionQualifier> actionQualifiers = db
    .select("SELECT CODE_REGEX, ACTION_NUMBER FROM ACTION_MAPPING")
    .get(rs -> new ActionQualifier(rs.getString("CODE_REGEX"), rs.getInt("ACTION_NUMBER")));

You could use a cache() operator to hold onto them and "replay" them to each subscriber, and this is valid. But the actionQualifiers may become stale as cache()would hold onto them indefinitely.

 Observable<ActionQualifier> actionQualifiers = db
    .select("SELECT CODE_REGEX, ACTION_NUMBER FROM ACTION_MAPPING")
    .get(rs -> new ActionQualifier(rs.getString("CODE_REGEX"), rs.getInt("ACTION_NUMBER")))
    .cache();

Dave Moten has created a clever solution that expires the cache and re-subscribes to the source. But ultimately you got to ask if it is easier to simply hold the actionQualifiers in a List, and refresh them in a manual way. You might as well not be bound to a monad anymore.

List<ActionQualifier> actionQualifiers = db
    .select("SELECT CODE_REGEX, ACTION_NUMBER FROM ACTION_MAPPING")
    .get(rs -> new ActionQualifier(rs.getString("CODE_REGEX"), rs.getInt("ACTION_NUMBER")))
    .toList().toBlocking().first();

Then you can always turn the saved List into an Observable at any time, if you in fact want to use it as an Observable.

 Observable.from(actionQualifiers).filter(aq -> aq.qualify("TXB.*"));

Either way, collections of expensive items can be challenging to work with. In some situations, it is easier to manage them statefully rather than functionally. You can probably get creative and find ways to maintain a reactive nature depending on your situation, but be mindful to not over-complicate it. However, if you have a very large, memory-intensive collection then maybe an Observable is valid to prevent caching from taking up memory. It really depends on what "expensive" means.

Case #3 Simple "Lookups" and Single-Step Monads

What is great about RxJava is its ability to compose multiple steps. Take these, then filter that, map to this, and reduce to that. You can create a long, elaborate chain of operations doing tons of work with little code.

Observable<Product> products = ...

Observable<Int> totalSoldUnits = products
    .filter(pd -> pd.getCategoryId() == 3)
    .map(pd -> pd.getSoldUnits())
    .reduce(0,(x,y) -> x + y)

But what if you are only interested in doing one step, like looking up a single value with an ID?

Observable<Category> category = Category.forId(263);

Is an Observable overkill in this case? Maybe. It might just be simpler to return the Category without being emitted through an Observable.

Category category = Category.forId(263);

Maybe an Observable is warranted if you expect more than one Category to be emitted, or you want to return an empty Observable rather than a null value if no Category is found for that ID. But as we will discover next in Case #4, this excessive use of Observable might create more boilerplate code rather than reduce it. But for now note if you are expecting a single value that is simply a "look up", or it requires only one step, consider not using an Observable.

Besides, if you really want to utilize an Observable for a given usage, you can always convert it to one later. You can even filter out any null value to make it empty.

Observable<Category> category = Observable.just(Category.forId(263))
    .filter(c -> c != null);

Case #4 Frequently Qualified Properties

Let's expand on Case #3 to make another point. Say you have this Product class.

public final class Product { 
    private final int id;
    private final String description;
    private final int categoryId;

    public Product(int id, String description, int categoryId) { 
        this.id = id;
        this.description = description;
        this.categoryId = categoryId;
    }
    public Observable<Category> getCategory() { 
        return Category.forId(categoryId);
    }
}

Notice the getCategory() method returns an Observable<Category>. If we frequently qualify on the Category, this could be pretty messy. Suppose each Category has a getGroup() returning an int, and we want to filter out an Observable<Product> for only products where the category's group is 5.

Observable<Product> products = ...

Observable<Product> productsInGroup5 = 
    products.flatMap(p -> p.getCategory().filter(c -> c.getGroup() == 5).map(p -> c));

For a simple task, this requires a lot of FlatMap Kung-Fu. We flatMap() each Product to its Category, then filter for Categories where the getGroup() is 5, and then map the Category back to the Product. If we take the Product class and make its getCategory() a non-Observable, this would be a lot simpler.

public Category getCategory() { 
    return Category.forId(categoryId);
}
Observable<Product> productsInGroup5 = 
    products.filter(p -> p.getCategory().getGroup() == 5);

In summary, if you have fields on a class that are frequently filtered/qualified on, you might want to consider not making it an Observable to avoid complexity. This is especially true if the property returns a single value and not a sequence of values.

Case #5 Capturing State

RxJava is very anti-state. This is a good thing. It allows us to compose a series of actions and behaviors rather than manually manage a series of states. This allows operations to be agnostic to threads, and you can compose concurrency at any time with ease into any Observable chain.

But I have noticed with complex business applications (which definitely benefit from reactive programming), you sometimes want to capture state especially when trying to gather context of how your algorithm came up with an action. This is critical for business reporting. The simplest example I can think of is holding on to a snapshot of history.

public final class PricePoint { 
    private final int id;
    private final int productId;
    private final BigDecimal price;
    private final ImmutableList<BigDecimal> historicalPricePoints;

    public PricePoint(int id, int productId, BigDecimal price) { 
        this.id = id;
        this.productId = productId;
        this.price = price;
        historicalPricePoints = HistoricalPricePoints.forProductId(productId);
    }
    public ImmutableList<BigDecimal> getHistoricalPricePoints() { 
        return historicalPricePoints;
    }
}

You could retrieve the historical price points reactively, and this is fine if the operation is not expensive.

public final class PricePoint { 
    private final int id;
    private final int productId;
    private final BigDecimal price;

    public PricePoint(int id, int productId, BigDecimal price) { 
        this.id = id;
        this.productId = productId;
        this.price = price;
    }
    public Observable<BigDecimal> getHistoricalPricePoints() { 
        return HistoricalPricePoints.forProductId(productId);
    }
}

But if it is expensive, this goes back to Case #2. Also, if you want to capture the historical price points at the time the PricePoint is constructed, an Observable might not be optimal either. You do in fact want to hold on to state, and an anti-state solution like RxJava might undermine this.

If you want to gather and retain different states for different properties so you can hold onto a context snapshot, you might want to use a traditional pull-based solution to build all that.

Summary

Reactive programming is definitely a game-changer and you should use it liberally. But be aware that RxJava tackles moderate to high complexity problems, and not necessarily simple ones. Some of these cases I identified above may be obvious to Rx veterans. But to newbies encouraged to build applications "reactive from the ground-up", it may not be so obvious.

Again, these are just my observations. Please comment below if you have any questions, additional cases, affirmations, disagreements, or thoughts.

Posted by Thomas Nield at <abbr class="published" itemprop="datePublished" title="2016-07-07T20:22:00-07:00" style="border: none;">8:22 PM</abbr>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,732評論 6 539
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,214評論 3 426
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,781評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,588評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,315評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,699評論 1 327
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,698評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,882評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,441評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,189評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,388評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,933評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,613評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,023評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,310評論 1 293
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,112評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,334評論 2 377