Activity Code

PHOTO EMBED

Tue Jun 07 2022 18:39:15 GMT+0000 (UTC)

Saved by @mueeza #kotlin

class MainActivity : AppCompatActivity() {

   lateinit var button: Button
   lateinit var counter: TextView
   val view_model:ViewModel = viewModel()

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)

       button = findViewById(R.id.button)

       counter = findViewById(R.id.counter)

       lifecycleScope.launch {
           repeatOnLifecycle(Lifecycle.State.STARTED) {
               (view_model as viewModel).stateFlow.collectLatest { number ->
                  counter.text = number.toString()
               }
           }
       }

       button.setOnClickListener{
           (view_model as viewModel).incrementCounter()
       }

   }

}

content_copyCOPY