MainActivity contains five pages built using Compose. Navgation will repeatedly create destination, causing the screen to load repeatedly. I added Log to two places in ArticlePage.kt to print the log.The following is the log corresponding to each operation.
The first generation of the application to open the log is
D/ArticlePage: ArticlePage page is created
D/ArticlePage: ArticlePage page is created
Log after performing refresh operation
I/ArticlePage: articles data change
I/ArticlePage: articles data change
Log when Navigation to other screen
D/ArticlePage: ArticlePage page is created
I/ArticlePage: articles data change
D/ArticlePage: ArticlePage page is created
I/ArticlePage: articles data change
Log when switch to the ArticlePage again
D/ArticlePage: ArticlePage page is created
I/ArticlePage: articles data change
D/ArticlePage: ArticlePage page is created
I/ArticlePage: articles data change
D/ArticlePage: ArticlePage page is created
I/ArticlePage: articles data change
Because every time the log prints articles data change, it means that my screen needs to be refreshed once, and the animation in the screen will be loaded repeatedly. Very influential to use.How can I set it up to avoid page repeated loading.
MainActivity.kt
HomePages.forEachIndexed { index, screen ->
selected = currentDestination == screen.route,
onClick = {
navController.navigate(screen.route) {
popUpTo(navController.graph.startDestinationId) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
}
)
}
MainActivityNavigation.kt
NavHost(navController, startDestination = HomePage.ArticlePage.route) {
composable(HomePage.ArticlePage.route) {
val viewModel:ArticleVM = hiltViewModel()
ArticlePage(activity,viewModel) //The parameter activity is MainActivity
}
}
ArticlePage.kt
This is a mixed screen containing View and Compose.FragmentArticlesBinding contains a RecyclerView and refresh control widget
@Composable
fun ArticlePage(
activity: MainActivity,
articleVM: ArticleVM,
) {
Log.d("ArticlePage", "ArticlePage page is created")
AndroidViewBinding(factory = FragmentArticlesBinding::inflate) {
...... //init refresh
// Directly monitor article data changes
articleVM.articles.observe(activity) {
Log.i("ArticlePage", "articles data change")
......... //other operations
}
}
}
ArticleVM.kt
@HiltViewModel
class ArticleVM @Inject constructor() : BaseVM() {
// article List declare
val articles = MutableLiveData<ReturnList<ArticleDetail>>()
}