Last active
May 28, 2018 04:04
-
-
Save Asutosh11/95edac7576d6702cb40ae7f35d051472 to your computer and use it in GitHub Desktop.
Simplest ViewModel & LiveData usage on Android
This file contains 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
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