Skip to content

Instantly share code, notes, and snippets.

@Asutosh11
Last active May 28, 2018 04:04
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 Asutosh11/95edac7576d6702cb40ae7f35d051472 to your computer and use it in GitHub Desktop.
Save Asutosh11/95edac7576d6702cb40ae7f35d051472 to your computer and use it in GitHub Desktop.
Simplest ViewModel & LiveData usage on Android
class DummyViewModel : ViewModel() {
var data : MutableLiveData<String> = MutableLiveData()
internal fun setData(some_value : String){
data.value = some_value
}
}
------------------------------------------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var viewModel = ViewModelProviders.of(this).get(DummyViewModel::class.java)
viewModel.setData("naaice")
viewModel.data.observe(
this, Observer { image ->
run {
Log.i("observed_path", image)
}
})
val handler = Handler()
val r = object:Runnable {
public override fun run() {
viewModel.setData("naaice 2222")
}
}
handler.postDelayed(r, 5000)
handler.postDelayed(r, 10000)
/**
* Output when MainActivity is on the Screen
* -----------------------------------------
*
* I/observed_path: naaice
* I/observed_path: naaice 2222
* I/observed_path: naaice 2222
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment