简体   繁体   English

如何使 Jetpack Compose 生命周期与 Fragment 生命周期兼容?

[英]how to make jetpack compose lifecycle compatible with Fragment life cycles?

My app previous was made using Fragments as pages.我以前的应用程序是使用 Fragments 作为页面制作的。 Now i'm integrating Jetpack Compose into my app.现在我正在将 Jetpack Compose 集成到我的应用程序中。 The pages are like this:页面是这样的:

HomePageFragment -> the home page made with traditional XML HomePageFragment -> 繁体制作的首页 XML

ItemListPageFragment -> a fragment wraps ComposeView that everything is done by Compose ItemListPageFragment -> 一个片段包装了 ComposeView,一切都由 Compose 完成

ItemDetailPageFragment -> item detail page made with traditional XML ItemDetailPageFragment -> 使用传统 XML 制作的商品详情页面

Here are the effects I want to achieve:下面是我想要实现的效果:

  • When entering ItemListPage, show loading then a list of items.当进入 ItemListPage 时,显示正在加载,然后是项目列表。 then user scroll down a bit, select an item, jump to ItemDetailPage然后用户向下滚动一点,select 一个项目,跳转到 ItemDetailPage
  • When go back from ItemDetailPage to ItemListPage, UI shouldn't reload, but stays at where it was left with.当 go 从 ItemDetailPage 返回到 ItemListPage 时,UI 不应重新加载,而是停留在原来的位置。

My ItemListPage is like this:我的 ItemListPage 是这样的:


@Composable
fun Content(){

   // third party lib that kind of like useSWR for React
   val states = useRequest(fetcher = {....})
   
   if(states.error) {...}
   if(states.loading) {....}

   // render list of items
   ....
}


right now it triggers fetch and loading UI when I go back from ItemDetailPage to ItemListPage.现在,当我 go 从 ItemDetailPage 返回到 ItemListPage 时,它会触发获取和加载 UI。

I think the issue is Fragment destroy views when "page-out".我认为问题是“分页”时片段会破坏视图。 Then when it is "back-to" page, it creates new ComposeView and triggered onLoad event.然后当它是“返回”页面时,它会创建新的 ComposeView 并触发 onLoad 事件。

Use ViewModel使用视图模型

OR或者

Use rememberSavable so that there won't be change even if there are any configuration changes使用rememberSavable这样即使有任何配置更改也不会更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM