airbnb / mavericks

Mavericks: Android on Autopilot
https://airbnb.io/mavericks/
Apache License 2.0
5.85k stars 499 forks source link

Feature Request - Allow retainValue parameter of type S.() -> Async<T> in MavericksRepository #673

Closed qiushui95 closed 7 months ago

qiushui95 commented 1 year ago

I am currently using the Mavericks library in my Android project and I am wondering if it would be possible to allow a lambda of type S.() -> Async to be used as the retainValue parameter in the execute method of the MavericksRepository class.

This feature would provide greater flexibility in managing the creation and retention of Async instances based on the current state of the repository.

If this is not possible, I would appreciate any suggestions on alternative approaches to achieving similar functionality.

Thank you for your time and consideration.

qiushui95 commented 1 year ago
data class DataInfo(val index: Int, val state: Async<Int>)
data class MainUS(val list: List<DataInfo> = emptyList()) : MavericksState`
class MainVM(initialState: MainUS) : MavericksViewModel<MainUS>(initialState) {
    companion object : MavericksViewModelFactory<MainVM, MainUS> {
        override fun initialState(viewModelContext: ViewModelContext): MainUS? {
            val list = (1..20).map { DataInfo(index = it, state = Uninitialized) }

            return MainUS(list)
        }

        override fun create(viewModelContext: ViewModelContext, state: MainUS): MainVM? {
            return MainVM(state)
        }
    }

    fun doWork(info: DataInfo) {

        flow {
            delay(1000)
            emit(Random.nextInt())
        }.execute(Dispatchers.IO) {

            val list = list.map { itemInfo ->
                itemInfo.takeUnless { it.index == info.index } ?: itemInfo.copy(state = it)
            }

            copy(list = list)
        }
    }
}