Skip to content

Instantly share code, notes, and snippets.

@alome007
Created January 17, 2023 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alome007/4d22d0bcf8c213703dfa70c1608497a0 to your computer and use it in GitHub Desktop.
Save alome007/4d22d0bcf8c213703dfa70c1608497a0 to your computer and use it in GitHub Desktop.
MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import me.astrocoder.blog.usingstateflow.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private val myViewModel: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//button on click, call our viewModel
binding.incrementBtn.setOnClickListener {
//increment our counter value:
myViewModel.incrementCounter()
}
//Launch myViewModel in a LifeCycleScope
lifecycleScope.launch {
//Repeat on LifeCycle ensures that the flow only emits data when needed
// (I.e when the app is not in the background, or when the UI is visible),
// this is helpful when a user presses the home button and our app goes into the background,
// as we don’t want to collect data might put our app at a risk of a crash,
// for example showing a modal when the app is in the background can cause it to crash
repeatOnLifecycle(Lifecycle.State.STARTED){
myViewModel.counter.collect{
binding.mTxt.text = it.toString()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment