Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View Lamartio's full-sized avatar

Danny Lamarti Lamartio

  • Elements
  • Almere
View GitHub Profile
@Lamartio
Lamartio / ViewModelFactory.kt
Last active May 10, 2019 08:13
ViewModelFactory
/*
* Copyright 2019 Danny Lamarti
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(LinearLayout(this).layout(User.observable) {
layout.orientation = LinearLayout.VERTICAL
layout.gravity = Gravity.CENTER
+textView {
+textView {
text = "This is plain text"
bind { user -> text = "${user.name}: ${user.age}" } // User is the argument
bind { text = "$name: $age" } // User is the this-pointer
}
typealias Observer<T> = T.(T) -> Unit
@Lamartio
Lamartio / BindableLayout.kt
Created September 24, 2018 07:39
kotlins_simple_layout_trick_pt2_view_extensions.kt
open class BindableLayout<T, V : ViewGroup>(
layout: V,
private val observable: Observable<T>
) : Layout<V>(layout) {
init {
layout.addOnAttachStateChangeListener(DisposableOnAttachStateChangeListener {
observable.subscribe(observers)
})
}
@Lamartio
Lamartio / BindableLayout.kt
Last active September 24, 2018 07:33
kotlins_simple_layout_trick_pt2_bind_implementation.kt
open class BindableLayout<T, V : ViewGroup>(layout: V) : Layout<V>(layout) {
private val observers = Observers()
fun bind(observer: Observer<T>) {
observers.add(observer)
}
private inner class Observers : ArrayList<Observer<T>>(), Consumer<T> {
data class User(val name: String = "Danny", val age: Int = 27) {
companion object {
fun asDataSource(): Observable<User> =
Observable
.interval(1, TimeUnit.SECONDS)
.scan(User()) { user, _ -> user.copy(age = user.age + 1) }
.observeOn(AndroidSchedulers.mainThread())
LinearLayout(this) layout {
// ...
}
infix fun <V : ViewGroup> V.layout(block: Layout<V>.() -> Unit): V =
also { Layout(it).run(block) }
class Layout<V : ViewGroup>(val layout: V) : ViewManager by layout, ViewParent by layout {}
LinearLayout(this) layout {
+textView {
text = "Hello world"
}
}
val Layout<*>.textView: TextView get() = TextView(context)
val Layout<*>.button: Button get() = Button(context)
LinearLayout(this) layout {
+TextView(context) {
text = "Hello world"
}
}
class Layout<V : ViewGroup>(val layout: V) : ViewManager by layout, ViewParent by layout {
// ...
LinearLayout(this) layout {
+TextView(context).apply {
text = "Hello world"
}
}
class Layout<V : ViewGroup>(val layout: V) : ViewManager by layout, ViewParent by layout {
val context = layout.context