jetpack使用_用jetpack撰写分页

jetpack使用

为什么要在意呢? (Why care?)

Probably many of you will agree with me saying that one of the most common components in mobile apps is a list. Lists very often are long but what users see is a portion of the list. So there is no point to load every single list item at once. This is where the Pagination concept helps us out. Long story short, long lists need to be separated into pages and loaded one page at the time.

也许很多人都会同意我的看法,移动应用程序中最常见的组件之一就是列表。 列表通常很长,但用户看到的只是列表的一部分。 因此,没有必要一次加载每个列表项。 这是分页概念可以帮助我们的地方。 长话短说,长列表需要分成几页,然后一次加载一页。

When I heard about Jetpack Compose Alpha being released. I thought “This is the right time to play with it”. I should mention that I am a big fan of Flutter, so building declarative UI feels like home for me. Since I am working in media, building news apps, there was no better feature for me to test than pagination.

当我听说Jetpack Compose Alpha被发布时。 我认为“现在是玩游戏的合适时间” 。 我应该提到我是Flutter的忠实拥护者,因此建立声明性UI对我来说就像家一样。 由于我从事媒体工作,开发新闻应用程序,因此没有比分页更好的测试功能了。

I think the title already spoiled how this ended up. Yes, it’s possible and yes it’s easy. Further down we will focus on How.

我认为标题已经破坏了它的结局。 是的,这是可能的,是的,这很容易。 往下看,我们将重点放在方法上。

可组合 (Composable)

If you are not familiar yet with the basics of Jetpack Compose, I recommend you read about that first and then come back here. I will wait.

如果您还不熟悉Jetpack Compose的基础知识,建议您先阅读有关内容,然后再回到这里。 我将等待。

When I started digging in, I asked myself, what is equivalent to the old RecyclerView. In Compose, it is a Column.

当我开始挖掘时,我问自己,什么和旧的RecyclerView等效。 在Compose中,它是Column

@Composable
fun SimpleList() {
    Column {
        Text("First item")
        Text("Second item")
        for (i in 0..10) {
            Text("Next $i item")
        }
    }
}

👆We can put as many elements into the Column as we want. We can add for or other statements if we want to. However, all those elements are composed at once. Imagine having a thousand elements. That is not the way to go.

👆我们可以根据需要在Column尽可能多的元素。 如果需要,我们可以添加for或其他语句。 但是,所有这些元素都是一次组成的。 想象一下有上千个元素。 那不是要走的路。

Fortunately, Jetpack Compose offers more. There is LazyColumnFor composable. It takes a list of items and builds each item on demand.

幸运的是,Jetpack Compose提供了更多功能。 有LazyColumnFor可组合的。 它获取项目列表并按需构建每个项目。

@Composable
fun LazyList() {
    val items = listOf("Dog", "Cat", "Monkey")//1000 of these
    LazyColumnFor(items = items) { item ->
        Text(text = item)
    }
}

Now, this is better. We can have our thousand items. Only items that are visible will be composed.

现在,这更好。 我们可以有上千种物品。 只有可见的项目才会被合成。

But this is not enough. That list of items should grow while we scroll down. We need to fetch more items. How can we tell if we have reached the end of the Column?

但这还不够。 当我们向下滚动时,该项目列表应该会增加。 我们需要获取更多物品。 我们如何知道是否到达Column的尽头?

The answer is: use LazyColumnForIndexed.

答案是:使用LazyColumnForIndexed

@Composable
fun LazyExampleWithIndex() {
    val items = listOf("Cat", "Dog", "Monkey")//1000 of these
    val lastIndex = items.lastIndex
    LazyColumnForIndexed(items = items) { index, item ->
        if (lastIndex == index) {
            onActive {
                //fetch more items from API
            }
        }
        Text(text = "Item $item")
    }
}

👆What happens here? We check if we are composing the last item in the Column. If we do, we call onActive {}. It’s a very handy function that is called ONLY once on first item composition. That is important because composable elements can be rebuilt over and over again as soon as data changes.

here这里发生了什么? 我们检查是否要组成Column的最后一项。 如果这样做,我们调用onActive {} 。 这是一个非常方便的函数,仅在第一个项目组合中被调用一次。 这很重要,因为可组合元素可以在数据更改后一遍又一遍地重建。

带页面的数据 (Data with pages)

As an example, I will use the news service I am working with on a daily basis. It supports pagination serving a limited number of articles and links to the next page.

例如,我将每天使用我正在使用的新闻服务。 它支持分页服务,提供数量有限的文章,并提供指向下一页的链接。

{
  "articles": [],
  "links": {
    "next": "/articles?sort=latest&offset=15&articleOffset=10&limit=10",
    "self": "/articles?sort=latest"
  }
}

It’s a very common solution for APIs. Once you get your first response, it will contain a link to the next page. Then you use that link to get a new response with a new link, merge results, and display them. Then repeat and repeat until data in the API will end.

这是API的非常常见的解决方案。 获得第一个回复后,它将包含指向下一页的链接。 然后,您可以使用该链接来获得带有新链接的新响应,合并结果并显示它们。 然后重复并重复直到API中的数据结束。

UI +数据=❤️ (UI + Data = ❤️)

Now it’s time to connect our data with composable UI. This is copied from a repository I have shared at the end of this article.

现在是时候将我们的数据与可组合的UI连接起来了。 这是从本文结尾处共享的存储库中复制的。

@ExperimentalCoroutinesApi
@Composable
fun LatestNewsFeed(viewModel: NewsViewModel) {
    val state = viewModel.newsState.collectAsState()
    val lastIndex = state.value.articles.lastIndex
    LazyColumnForIndexed(items = state.value.articles) { i, newsItem ->
        if (lastIndex == i) {
            onActive {
                viewModel.getMoreNews()
            }
        }
        NewsCard(newsItem) {
            viewModel.onSelectedNews(newsItem)
        }
    }
}

👆This is composable LatestNewsFeed which gets NewsViewModel as a data source. That view model provides StateFlow which is a coroutine class that streams data whenever it changes. However, we are not working directly on this class. We call collectAsState() extension function to turn it into State object which is a part of Jetpack Compose. That state triggers the recomposition of the UI whenever data under the hood changes.

👆This是可组合的LatestNewsFeed它获取NewsViewModel作为数据源。 该视图模型提供了StateFlow ,它是一个协程类,可在数据更改时流式传输数据。 但是,我们不直接从事此类课程。 我们调用collectAsState()扩展功能将其转换为State对象,该对象是Jetpack Compose的一部分。 每当引擎盖下的数据发生更改时,该状态就会触发UI的重组。

You can easily replace StateFlow with RxJava or LiveData. Jetpack Compose supports them all.

您可以轻松地更换StateFlow与RxJava或LiveData 。 Jetpack Compose支持所有这些功能。

Inside onActive{} I am calling the view model to fetch more data. Once data is fetched, State is triggered and the entire column is rebuilt with new data.

onActive{}内部,我正在调用视图模型以获取更多数据。 提取数据后,将触发State并使用新数据重建整个列。

I have prepared a fully working example here 👇

我在这里准备了一个完整的示例

I hope you enjoyed this article.

希望您喜欢这篇文章。

翻译自: https://medium.com/schibsted-tech-polska/list-pagination-with-jetpack-compose-6c25da053858

jetpack使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值