Skip to content

Instantly share code, notes, and snippets.

@stevdza-san
Created July 2, 2022 06:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevdza-san/f259136586e53620c1cc58339ac1b115 to your computer and use it in GitHub Desktop.
Save stevdza-san/f259136586e53620c1cc58339ac1b115 to your computer and use it in GitHub Desktop.
collectAsStateWithLifecycle() example
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.comptest.ui.theme.CompTestTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
@ExperimentalLifecycleComposeApi
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CompTestTheme {
MyScreen()
}
}
}
}
@ExperimentalLifecycleComposeApi
@Composable
fun MyScreen(myViewModel: MyViewModel = viewModel()) {
val value by myViewModel.myStateFlow.collectAsStateWithLifecycle()
// val value by myViewModel.myStateFlow.collectAsState()
LaunchedEffect(key1 = value) {
Log.d("MyScreen", "$value")
}
}
class MyViewModel : ViewModel() {
private val myFlow = flow {
(0..100).forEach {
emit(it)
delay(1000)
}
}
val myStateFlow = myFlow.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = 0
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment