Skip to content

Instantly share code, notes, and snippets.

View lmiotti's full-sized avatar

Lucas Miotti lmiotti

View GitHub Profile
@lmiotti
lmiotti / MainScreen.kt
Created January 4, 2024 16:19
SharedFlow example
@Composable
fun MainScreen(
viewModel: SomeViewModel
) {
val lifecycle = LocalLifecycleOwner.current
LaunchedEffect(Unit) {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.sharedFlow.collectLatest {
Log.d("MainActivity", it.toString())
}
@Composable
fun MainScreen(
viewModel: SomeViewModel
) {
val state = viewModel.stateFlow.collectAsStateWithLifecycle()
Log.d("MainActivity", state.value.toString())
}
@lmiotti
lmiotti / MainScreen.kt
Created January 4, 2024 14:24
Flow examplie
@Composable
fun MainScreen(
viewModel: SomeViewModel
) {
val result = viewModel.flow.collectAsStateWithLifecycle(initialValue = 0)
Log.d("MainActivity", result.value.toString())
}
@lmiotti
lmiotti / SomeViewModel.kt
Last active January 4, 2024 21:13
LiveData & Dispatchers example
class SomeViewModel constructor(
private val getUserUseCase: GetUserUseCase,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
): ViewModel() {
// ... Rest of your code ...
private val _liveData = MutableLiveData<User>()
val liveData: LiveData<User>
get() = _liveData
@lmiotti
lmiotti / MainActivity.kt
Last active January 4, 2024 21:14
LiveData example
class MainActivity: AppCompatActivity() {
private val viewModel: SomeViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ... Rest of your code ...
viewModel.liveData.observe(this) {
// DO SOMETHING