3

在Google發佈的最新Android Architecture Components庫中,我們在Transformations類中有兩個靜態函數。雖然map功能較爲簡單,並容易理解的,我發現很難正確理解switchMap功能。如何以及在哪裏使用Transformations.switchMap?

switchMap的官方文檔可以找到here

有人可以解釋如何以及在哪裏使用switchMap函數和一個實際的例子?

回答

2

map()功能

LiveData userLiveData = ...; 
LiveData userName = Transformations.map(userLiveData, user -> { 
    return user.firstName + " " + user.lastName; // Returns String 
}); 

每次的userLiveData的值發生變化,userName將被更新到。請注意,我們正在返回String

switchMap()功能:

MutableLiveData userIdLiveData = ...; 
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id -> 
    repository.getUserById(id)); // Returns LiveData 

void setUserId(String userId) { 
    this.userIdLiveData.setValue(userId); 
} 

每次的userIdLiveData的值發生變化,repository.getUserById(id)將被調用,就像地圖功能。但repository.getUserById(id)返回LiveData。所以每當repository.getUserById(id)返回的LiveData的值發生變化時,userLiveData的值也會改變。所以userLiveData的值將取決於userIdLiveData的變化以及repository.getUserById(id)的值的變化。

switchMap()的實際示例:假設您有一個用戶配置文件,其中包含一個關注按鈕和一個用於設置其他配置文件信息的下一個配置文件按鈕。下一個配置文件按鈕將調用setUserId()與另一個ID,所以userLiveData將改變,用戶界面將改變。 Follow按鈕會調用DAO爲該用戶添加一個追隨者,因此用戶將擁有301個追隨者而不是300個。userLiveData將具有來自DAO的存儲庫的此更新。

相關問題