Created
April 5, 2018 06:23
-
-
Save ozodrukh/7b51d632ba5b783d38d95838f475b866 to your computer and use it in GitHub Desktop.
Extensions to Android Arch Components
This file contains hidden or 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
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