Skip to content

Instantly share code, notes, and snippets.

View psteiger's full-sized avatar
🎯
Focusing

Patrick Steiger psteiger

🎯
Focusing
View GitHub Profile
fun <T> Resource<T>.onSuccess(
onSuccess: (data: T) -> Unit
): Resource<T> {
if (this is Resource.Success<T>)
onSuccess(data)
return this
}
fun <T> Resource<T>.onLoading(
class UserFragment : Fragment() {
private var usersViewModel: UserViewModel? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_users, container, false)
class UsersViewModel : ViewModel() {
private val usersSnapLiveData: LiveData<Resource<DataSnapshot>> by lazy {
UsersSnapLiveData()
}
val usersLiveData: LiveData<Resource<HashMap<String, User>>> by lazy {
usersSnapLiveData.mapGetValue<HashMap<String, User>>()
}
inline fun <reified T> LiveData<Resource<DataSnapshot>>.mapGetValue(): LiveData<Resource<T>> = map {
it.getTypedValueResource<T>()
}
inline fun <reified T> Resource<DataSnapshot>.getTypedValueResource(): Resource<T> = mapResource {
it.getTypedValue<T>()
}
class UsersViewModel : ViewModel() {
private val usersSnapLiveData: LiveData<Resource<DataSnapshot>> by lazy {
UsersSnapLiveData()
}
val usersLiveData: LiveData<Resource<HashMap<String, User>>> by lazy {
usersSnapLiveData.mapLiveDataResource<
DataSnapshot, // from
HashMap<String, User> // to
inline fun <reified T> DataSnapshot.getTypedValue(): T {
val genericTypeIndicator = object : GenericTypeIndicator<T>() {}
return getValue(genericTypeIndicator)!!
}
sealed class Resource<out T> {
data class Success<out T>(val data: T) : Resource<T>()
data class Loading<out T>(val partialData: T? = null) : Resource<T>()
data class Failure<out T>(val throwable: Throwable? = null) : Resource<T>()
val extractData: T? get() = when (this) {
is Success -> data
is Loading -> partialData
is Failure -> null
inline fun <X, Y> LiveData<Resource<X>>.mapLiveDataResource(
crossinline transform: (X) -> Y
): LiveData<Resource<Y>> =
map { it.mapResource(transform) }
// map from androidx.lifecycle:lifecycle-livedata-ktx
// Equivalent to Transformations.map(source, func)
class UsersSnapLiveData : FirebaseResourceLiveData("users")
open class FirebaseResourceLiveData : LiveData<Resource<DataSnapshot>> {
init {
value = Resource.Loading()
}
constructor(path: String) {
query = FirebaseDatabase.getInstance().getReference(path)
}