Daniel Burnhan
07/22/2021, 1:36 PMclass MyViewModel(model: Model) {
val userLoggedInFlow = model.usernameFlow.map { it != null } // returnes if there is a username
}
@Composable
fun myView(viewModel: MyViewModel){
val state = viewModel.userLoggedInFlow.asLiveData().observeAsState()
if(state.value != null){
//Show stuff here
}
else {
//navigate to the login screen
}
}
Adam Powell
07/22/2021, 5:02 PM.asLiveData()
is creating a new LiveData
from viewModel.userLoggedInFlow
every time myView
recomposes, and since you read state.value
in the same recompose scope, that means that every time state.value
changes you create a new LiveData, remove the old LiveData observer from the old LiveData, then add a new observer to the new LiveData, which may then emit a new value when it hits onActive after recomposition completes.Adam Powell
07/22/2021, 5:03 PMAdam Powell
07/22/2021, 5:05 PMval state = remember(viewModel) {
viewModel.userLoggedInFlow.asLiveData()
}.observeAsState()
You could choose to use viewModel.userLoggedInFlow
as the remember key instead of viewModel
, but since they're 1-1 here it'll have the same results and it's not uncommon for ViewModel methods to return new observable object instances on access depending on some implementation details, so it's not a bad habit to get used toIan Lake
07/22/2021, 6:29 PMasLiveData()
at all here given that Compose supports Flow directly with collectAsState()
?Adam Powell
07/22/2021, 7:43 PM.flowWithLifecycle
and remember
as described aboveJeff
07/22/2021, 10:03 PM@Composable
fun <T> rememberFlowWithLifecycle(
flow: Flow<T>,
lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): Flow<T> = remember(flow, lifecycle) {
flow.flowWithLifecycle(
lifecycle = lifecycle,
minActiveState = minActiveState
)
}
Adam Powell
07/22/2021, 10:10 PMval lifecycleOwner = LocalLifecycleOwner.current
val current by produceState(initial, flow, lifecycleOwner) {
flow.flowWithLifecycle(lifecycleOwner.lifecycle)
.otherOperators(...)
.collect { value = it }
}
Adam Powell
07/22/2021, 10:11 PMremember
-ing operators in use cases where you want a filter/map/something or otherAdam Powell
07/22/2021, 10:11 PM.collectAsState
is doing 🙂nglauber
07/23/2021, 2:00 AMrememberFlowWithLifecycle
function…? I wrote one by myself to my current project 😅
@Composable
fun <T> Flow<T>.flowInLifecycle(): Flow<T> {
val lifecycleOwner = LocalLifecycleOwner.current
return remember(this, lifecycleOwner) {
this.flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED)
}
}
Adam Powell
07/23/2021, 2:13 AMAdam Powell
07/23/2021, 2:13 AMNick
08/20/2021, 2:00 PMFlorian
09/12/2021, 8:05 AMFlorian
09/12/2021, 8:05 AMAdam Powell
09/12/2021, 3:56 PMFlorian
09/19/2021, 2:09 PM