Room Flow – How to handle updates of dynamic-based param request?

Given a room Database and a request with a DateTime based parameter :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Transaction
@Query("SELECT * FROM itemModel WHERE datetime(datetime(`end`), 'localtime') > datetime(:minDate, 'localtime') ORDER BY `end` ASC")
fun getFlow(
minDate: LocalDateTime,
): Flow<List<ItemModel>>
</code>
<code>@Transaction @Query("SELECT * FROM itemModel WHERE datetime(datetime(`end`), 'localtime') > datetime(:minDate, 'localtime') ORDER BY `end` ASC") fun getFlow( minDate: LocalDateTime, ): Flow<List<ItemModel>> </code>
@Transaction
@Query("SELECT * FROM itemModel WHERE datetime(datetime(`end`), 'localtime') >  datetime(:minDate, 'localtime') ORDER BY `end` ASC")
fun getFlow(
    minDate: LocalDateTime,
): Flow<List<ItemModel>>

=> Based on the minDate param, data returned from the request should change over time (even if database has no data changes)

How to handle flow updates ? Because :

  • nothing change database side (so the flow will never get notified of changes)
  • only the date in the request (should) change but once the flow is loaded, it seems the SQL request keeps its params like it was first called with.

I init my flow like this :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var items: StateFlow<List<ItemModel>>
fun initItemsFlow(context: Context) {
items = getAllRecords(context).stateIn(
scope = coroutineScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = emptyList(),
)
}
</code>
<code>var items: StateFlow<List<ItemModel>> fun initItemsFlow(context: Context) { items = getAllRecords(context).stateIn( scope = coroutineScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = emptyList(), ) } </code>
var items: StateFlow<List<ItemModel>>
fun initItemsFlow(context: Context) {
    items = getAllRecords(context).stateIn(
        scope = coroutineScope,
        started = SharingStarted.WhileSubscribed(5_000),
        initialValue = emptyList(),
    )
}

Should I manually call initItemsFlow again when I need (= re-seting from scratch the whole flow) or is there a better flow/room mechanims to handle that ?

Thanks

I don’t know if that is just caused by a copy&paste error but the dao’s getFlow needs a LocalDateTime parameter where in the (I guess) view model you only call getAllRecords with a Context parameter. It is unclear how the functions are related so in the rest of my answer I will ignore getAllRecords because it doesn’t seem to serve any purpose that is relevant to the problem at hand.

Instead I will outline how you can change the getFlow‘s minDate parameter while still returning the same StateFlow. You can then adapt this to your actual code.

The solution is to introduce another flow – a MutableStateFlow – to store the minDate. A MutableStateFlow is like a variable, it represents a single value that can be changed, so whenever you want to update minDate you can just set the MutableStateFlow’s value. Since a MutableStateFlow is also a flow you can transform its value using any of the flow transformation functions. In this case you want to switch out the flow with the one returned from getFlow.

Assuming you want to expose your database flow in the view model and also use it to update the minDate parameter then what I described above could look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class MyViewModel(
dao: MyDao,
) : ViewModel() {
private val minDate = MutableStateFlow<LocalDateTime?>(null)
val items: StateFlow<List<ItemModel>> = minDate
.flatMapLatest {
if (it == null) flowOf(emptyList())
else dao.getFlow(it)
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = emptyList(),
)
fun updateMinDate(date: LocalDateTime) {
minDate.value = date
}
}
</code>
<code>class MyViewModel( dao: MyDao, ) : ViewModel() { private val minDate = MutableStateFlow<LocalDateTime?>(null) val items: StateFlow<List<ItemModel>> = minDate .flatMapLatest { if (it == null) flowOf(emptyList()) else dao.getFlow(it) } .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = emptyList(), ) fun updateMinDate(date: LocalDateTime) { minDate.value = date } } </code>
class MyViewModel(
    dao: MyDao,
) : ViewModel() {
    private val minDate = MutableStateFlow<LocalDateTime?>(null)

    val items: StateFlow<List<ItemModel>> = minDate
        .flatMapLatest {
            if (it == null) flowOf(emptyList())
            else dao.getFlow(it)
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = emptyList(),
        )

    fun updateMinDate(date: LocalDateTime) {
        minDate.value = date
    }
}

Here minDate is the new MutableStateFlow. It is used as the basis for the items property and flatMapLatest is used to switch to another flow based on minDate‘s content. That transforms the Flow<LocalDateTime> to a Flow<List<ItemModel>> by calling getFlow with the MutableStateFlow’s value as parameter.

Then that flow is converted to a StateFlow, ready to be collected by the UI. You should use the viewModelScope for that and not some other scope. Note that you do not need to switch to the IO dispatcher here, that is done internally by the Room library.

Now, whenever you call updateMinDate the items flow is automatically updated with this new date. Also any changes in the databse will cause the StateFlow to update. This is the usual way how to modify a flow without leaving the world of flows.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật