https://kotlinlang.org logo
#compose
Title
# compose
a

Ashwani Singh

11/13/2020, 9:14 AM
Hi All, How to convert below code into compose:
Copy code
private fun subscribeObservers() {
    homePageViewModel.viewState.observe(this) { viewState ->
        if (viewState != null) {
            viewState.pageUILayoutList?.let { pageUILayoutList ->
                printLogD("HomePageFragment | pageUILayoutList", pageUILayoutList.toString())
            }

            viewState.allModulesForPage?.let { allModulesContent ->
                printLogD("HomePageFragment | allContents", "" + allModulesContent.toString())

            }
        }
    }
}
I used below code, but its not work
Copy code
val homePageViewModel = (ContextAmbient.current as DashboardActivity).homePageViewModel
onActive {
    homePageViewModel.setStateEvent(
        HomePageStateEvent.GetPageModuleEvent()
    )
    homePageViewModel.setStateEvent(
        HomePageStateEvent.GetContentEvent()
    )
}
val viewState: HomePageViewState by homePageViewModel.viewState.observeAsState(
    HomePageViewState()
)
var pageUIMap: HashMap<String, String>? = null
if (viewState.pageUILayoutList != null) {
  // But not getting any call here
}
🧵 1
z

Zach Klippenstein (he/him) [MOD]

11/13/2020, 3:40 PM
Your second code block looks completely different than the first. It’s more straightforward:
Copy code
@Composable private fun subscribeObservers() {
    val viewState by homePageViewModel.viewState.observeAsState()
    onCommit(viewState) {
        if (viewState != null) {
            viewState.pageUILayoutList?.let { pageUILayoutList ->
                printLogD("HomePageFragment | pageUILayoutList", pageUILayoutList.toString())
            }
            viewState.allModulesForPage?.let { allModulesContent ->
                printLogD("HomePageFragment | allContents", "" + allModulesContent.toString())
            }
        }
    }
}
Although using Compose just to observe like this is odd, it would probably be better to observe in a coroutine using
LaunchedEffect
.
a

Ashwani Singh

11/17/2020, 4:36 PM
I use above code. not getting any call back.
z

Zach Klippenstein (he/him) [MOD]

11/17/2020, 4:41 PM
What callback are you expecting? There are no function calls to your view model in your first snippet, and I just converted that to Compose.
Your first and your second snippets are doing completely different things, so I wasn’t entirely sure what you were asking
2 Views