Skip to content

Instantly share code, notes, and snippets.

View jorgecasariego's full-sized avatar
:bowtie:

Jorge Casariego jorgecasariego

:bowtie:
View GitHub Profile
class SmartPhone(
val manufacture: String?,
val model: String?,
val storage: String?,
val screenSize: String?) {
data class Builder(
var manufacture: String? = null,
var model: String? = null,
var storage: String? = null,
import java.util.*
import kotlin.properties.Delegates
interface ValueChangedListener {
fun onValueChanged(newValue: String)
}
class PrintingTextChangedListener: ValueChangedListener {
override fun onValueChanged(newValue: String) {
println("Value of the text is: $newValue")
var text: String by Delegates.observable(
initialValue = "",
onChange = {
property, oldValue, newValue ->
listener.onValueChanged(newValue)
}
)
class MyFragment : Fragment() {
private lateinit var viewModel: MyViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
}
}
class MyViewModel : ViewModel() {
// Stored cached bitmap.
private var cachedBitmap: Bitmap? = null
// Retrieves the image.
fun getImage(): Bitmap {
// If the image is not already cached, download it and cache it.
if (cachedBitmap == null) {
cachedBitmap = downloadImage()
class MainFragment : Fragment() {
private lateinit var viewModel: MainViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
imageView.setImageBitmap(viewModel.getImage())
}
}
class MyViewModel : ViewModel() {
val imageLiveData = MutableLiveData<Bitmap>()
fun getImage() {
// ...
}
}
class MyFragment : Fragment() {
private lateinit var viewModel: MainViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
// We observe the bitmap emitted from `imageLiveData` and
// display it in the `ImageView`.
viewModel.imageLiveData.observe(this, Observer {
imageView.setImageBitmap(it)
class MyViewModel : ViewModel() {
// Some image downloader class.
val imageDownloader = ImageDownloader()
val imageLiveData = MutableLiveData<Bitmap>()
fun getImage() {
// If we don't have a value already pushed to the live data
// and the download is not in progress, start a new one.
if (imageLiveData.value == null && !imageDownloader.isDownloading) {
// This is just some sample API that uses RxJava, but
class ViewModel: ViewModel() {
fun fetchDocs() {
get("developer.android.com") { result ->
show(result)
}
}
}