Skip to content

Instantly share code, notes, and snippets.

@Atternatt
Last active September 21, 2017 04:56
Show Gist options
  • Save Atternatt/b5336aec4bfb4f8214237327fdfaccbc to your computer and use it in GitHub Desktop.
Save Atternatt/b5336aec4bfb4f8214237327fdfaccbc to your computer and use it in GitHub Desktop.
Truquis
import android.databinding.Observable as DataBindingObservable
private inline fun <reified T : DataBindingObservable, R : Any?> T.observe(
crossinline block: (T) -> R
): Observable<R> = create { subscriber ->
object : android.databinding.Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(observable: DataBindingObservable, id: Int) = try {
subscriber.onNext(block(observable as T))
} catch (e: Exception) {
subscriber.onError(e)
}
}.let {
subscriber.setCancellable { this.removeOnPropertyChangedCallback(it) }
this.addOnPropertyChangedCallback(it)
}
}
fun <T : Any> ObservableField<T>.observe() = observe { it() }
operator fun <T : Any?> ObservableField<T>.invoke(): T = get()
//así se usa
val concertList: ObservableField<List<Concert>> = ObservableField(listOf())
compositeDisposable += concertList.observe().subscribe { numberOfResults.set(it.size) }
internal val context: Context by lazy { MyCustomApplication.appContext }
val Int.sp: Float
get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, this.toFloat(), context.resources.displayMetrics)
val Int.dp: Float
get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), context.resources.displayMetrics)
fun Float.digits(numOfDigits: Int): String {
return String.format("%.${numOfDigits}f",this)
}
fun Long.fromMillistoDays(): Int {
return (this/86400000).toInt()
}
fun Long.fromMillisToWeeks(): Int {
return this.fromMillistoDays() / 7
}
fun TextView.textEvents(): Observable<CharSequence> {
return Observable.create {
if (it.isDisposed.not()) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
it.onNext(s)
}
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment