airbnb / mavericks

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

How to initiate multiple requests with uniform processing status #627

Closed Sunyuwumengsheng closed 2 years ago

Sunyuwumengsheng commented 2 years ago

I have two requests A and B. When the page is initialized, I need to request both A and B, and then I need to request B separately.I do now, but think it's problematic.

init { getBanner() getArticle(0) }

fun getBanner() = withState { state ->
    if (state.bannerRequest is Loading) return@withState

    suspend {
        api.getBanner()

    }.execute {
        copy(
            banner = it()?.data ?: emptyList(),
            bannerRequest = it
        )
    }
}

fun getArticle(page: Int) = withState { state ->
        if (state.articleRequest is Loading) return@withState

        suspend {
            api.getArticle(page)
        }.execute {
            copy(
                articles = it()?.data ?: Article(),
                articleRequest = it
            )
        }
    }
gpeal commented 2 years ago

I'm not sure I understand your question. One opportunity for improvement is to make articles and banner derived props like this:

data class YourState(
    val bannerRequest: Async<BannerRequest> = Uninitialized,
    val articleRequest: Async<ArticleRequest> = Unitialized,
) : MavericksState {
    val banner = bannerRequest() ?: emptyList()
    val article = articleRequest()?.data ?: article
}

Then your execute can look like

suspend {
    api.getArticle(page)
}.execute { copy(articleRequest = it) }
Sunyuwumengsheng commented 2 years ago

sorry my english is not good The effect I want is something like this suspend { zip(api.getBanner(), api.getArticle(page)) }.execute { copy( bannerRequest= it.bannerRequest articleRequest = it.articleRequest ) }

gpeal commented 2 years ago

Sounds like you got it working 😄