Created
July 2, 2022 06:32
-
-
Save stevdza-san/f259136586e53620c1cc58339ac1b115 to your computer and use it in GitHub Desktop.
collectAsStateWithLifecycle() example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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