Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extensions to Android Arch Components
package uz.gap.messenger.ext
import android.arch.lifecycle.*
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import uz.gap.messenger.connection.SocketModel.MessageStatus
/**
* created at 3/31/18
*
* @author Ozodrukh
* @version 1.0
*/
inline fun <reified T : ViewModel> FragmentActivity.viewModelOf(tag: String? = null): T {
return if (tag == null) {
ViewModelProviders.of(this).get(T::class.java)
} else {
ViewModelProviders.of(this).get(tag, T::class.java)
}
}
inline fun <reified T : ViewModel> Fragment.viewModelOf(tag: String? = null): T {
return if (tag == null) {
ViewModelProviders.of(this).get(T::class.java)
} else {
ViewModelProviders.of(this).get(tag, T::class.java)
}
}
inline fun <reified T : ViewModel> Fragment.activityViewModelOf(tag: String? = null): T {
return if (tag == null) {
ViewModelProviders.of(activity!!).get(T::class.java)
} else {
ViewModelProviders.of(activity!!).get(tag, T::class.java)
}
}
/**
* Simple observer that used with kotlin to avoid null checks iach time
*/
inline fun <T> LiveData<T>.safeObserve(owner: LifecycleOwner, crossinline block: (T) -> Unit) {
observe(owner, Observer { response -> response?.let(block) })
}
fun <K, T> LiveData<K>.then(transformer: (K) -> LiveData<T>?): LiveData<T> {
return Transformations.switchMap<K, T>(this, transformer)
}
inline fun <T, K> LiveData<MessageStatus<T>>.thenWhenResponded(crossinline transformer: (MessageStatus<T>)
-> LiveData<MessageStatus<K>>?): LiveData<MessageStatus<K>> {
return then {
return@then if (it.delivered() && it.responded()) transformer(it) else null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment