Code Monkey home page Code Monkey logo

livedata-ktx's Introduction

GitHub license Download Build Status

livedata-ktx

Kotlin extension for LiveData. This library focuses on three things:

  • Kotlin friendly.
  • Preserve immutability.
  • Extensibility.

About Kotlin friendly, thanks to androidx.lifecycle:livedata:2.0.0 release, you can explicitly set optional type for LiveData. LiveData and LiveData<Boolean?> are supported now. However, you can still set null value, for instance:

// Allow to set null value to LiveData
val liveData = MutableLiveData<Boolean>()
liveData.value = null

// LiveDataKtx doesn't allow to null value
val liveData = MutableLiveDataKtx<Boolean>()
liveData.value = null // doesn't allow

// Set nullable in LiveDataKtx
val liveData = MutableLiveDataKtx<Boolean?>()
liveData.value = null

README For 1.x

README For 2.x

Getting Started

To add LiveData KTX to your project, add the following to your app module's build.gradle:

implementation "com.shopify:livedata-ktx:VERSION"

Usage

From LiveData to LiveDataKtx

val liveData = LiveData<Boolean>()
val liveDataKtx = liveData.toKtx()
val nullableLiveDataKtx = liveData.toNullableKtx()
val anotherNullableLiveDataKtx = LiveDataKtx<Boolean?>()

val mutableLiveData = MutableLiveData<Boolean>()
val mutableLiveDataKtx = mutableLiveData.toKtx()
val nullableMutableLiveDataKtx = mutableLiveData.toNullableKtx()
val anotherNullableMutableLiveDataKtx = MutableLiveDataKtx<Boolean?>()

val mediatorLiveData = MediatorLiveData<Boolean>()
val mediatorLiveDataKtx = mediatorLiveData.toKtx()
val nullableMediatorLiveDataKtx = mediatorLiveData.toNullableKtx()
val anotherNullableMediatorLiveDataKtx = MediatorLiveDataKtx<Boolean?>()

Chaining LiveData

val liveData = MutableLiveDataKtx<Boolean>()
liveData
  .filter { it == false }
  .map { true }
  .observe(lifecycleOwner, Observer { result ->
    // result is non-null and always true
  })

PublishLiveData (SingleLiveData in version 2.x)

It is a lifecycle-aware observable that sends only new updates after subscription, used for events like navigation and Snackbar messages. livedata-ktx has different implementation comparing to SingleLiveEvent from google samples android-architecture.

val liveData = PublishLiveDataKtx<Int>()
val actual = mutableListOf<Int>()
val observer = Observer<Int> { actual.add(it) }
liveData.value = -1

liveData.observeForever(observer)
liveData.value = 0
liveData.removeObserver(observer)

assertEquals(listOf(0), actual)
actual.clear()

liveData.value = 1
liveData.value = 2
liveData.observeForever(observer)
liveData.value = 3

assertEquals(listOf(3), actual)

For more use cases, please see the tests at LiveDataKtxTest.kt

Use safeValue

LiveDataKtx will throw NPE if you try to get value when it supposes to be nonNull. Use safeValue in this case.

val liveDataKtx = MutableLiveDataKtx<Boolean>()

// Throw NPE if the value hasn't been set yet as it is defined as nonNull <Boolean>
liveDataKtx.value

// This works fine as the value has been set
liveDataKtx.value = true
liveDataKtx.value

// safeValue always returns nullable value and does not throw NPE
liveDataKtx.safeValue

// observe doesn't throw NPE even when the value hasn't been set
liveDataKtx.observe(...)

Feel missing methods

It is easy to add your custom extension without requiring to send a PR. For example:

/**
 * filter
 */
private class FilterOperator<T>(val predicate: (T) -> Boolean) : Operator<T, T> {

    override fun run(output: MediatorLiveDataKtx<T>, value: T) {
        if (predicate.invoke(value)) {
            output.value = value
        }
    }
}

fun <T> LiveDataKtx<T>.filter(predicate: (T) -> Boolean): LiveDataKtx<T> =
    Extension.create(this, FilterOperator(predicate))

fun <T> MutableLiveDataKtx<T>.filter(predicate: (T) -> Boolean): MutableLiveDataKtx<T> =
    Extension.create(this, FilterOperator(predicate))

fun <T> MediatorLiveDataKtx<T>.filter(predicate: (T) -> Boolean): MediatorLiveDataKtx<T> =
    Extension.create(this, FilterOperator(predicate))

Contributing

Any contributions are welcome! Please check the CONTRIBUTING guideline before submitting a new issue. Wanna send PR? Click HERE

Maintainers

License

The MIT License (MIT)

Copyright (c) 2018, 2019 Shopify Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

livedata-ktx's People

Contributors

henrytao-me avatar pgrimaud avatar takahirom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

livedata-ktx's Issues

PublishLiveDataKtx not remove observer by lifecycle event

Code from https://github.com/Shopify/livedata-ktx/blob/master/livedata-ktx/src/main/java/com/shopify/livedataktx/PublishLiveDataKtx.kt:

   override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        val observeSinceVersion = version
        val wrapper = observerWrappers.getOrElse(observer, Observer {
            if (!isPublish || version > observeSinceVersion) {
                observer.onChanged(it)
            }
        })
        observerWrappers.putIfAbsent(observer, wrapper)
        super.observe(owner, wrapper)
    }

    override fun observeForever(observer: Observer<in T>) {
        val observeSinceVersion = version
        val wrapper = observerWrappers.getOrElse(observer, Observer {
            if (!isPublish || version > observeSinceVersion) {
                observer.onChanged(it)
            }
        })
        observerWrappers.putIfAbsent(observer, wrapper)
        super.observeForever(wrapper)
    }

    override fun removeObserver(observer: Observer<in T>) {
        observerWrappers.get(observer)?.let { super.removeObserver(it) }
        observerWrappers.removeIfPresent(observer)
    }

When we call observeForever(), all looks good and calling removeObserver() with same Observer working as expected.

But if we call observe() and later lifecycle move to Destroyed state, system call removeObserver() with wrapped Observer, and we try to find it in observedWrappers among non-wrapped observers. Pair instances with weak references to observers just accumulated in array until livedata instance not GCed.

I don't know clear solution of this problem, suppose we can check wrapped and non-wrapped observers both when removing.

remove @Suppress("DEPRECATION")

Hi, I want to remove the @Suppress("DEPRECATION") at LiveData.kt

I want to know why deprication of SupportMediatorLiveData#observe() is suppressed.

I think It's better that showing an depricated warning when using the methods above, because Removable has a method removeObserver() to remove an observer but that does not work since removable has a different observer from the one actually observing.

And I also want to confirm that the reason you are depricating the method is what I mentioned above.

thank you in advance.

Multiple implementation issue in android studio 3.5

Overload resolution ambiguity all this function match

fun <T, R> LiveData.map(mapper: (T?) -> R?): LiveData = createMediator(this, MapExt<T, R>(mapper))
fun <T, R> SupportMediatorLiveData.map(mapper: (T) -> R): SupportMediatorLiveData = createMediator(this, MapExt<T, R>({
return@MapExt mapper(it!!)!!
}))

Shows error on using map extension function chaos in choosing map function .

MutableLiveDataKtx is not subtype of MutableLiveData

There are places where MutableLiveData is required, for example in two way data binding. It may be better to make MutableLiveDataKtx a subtype of MutableLiveData as these dependencies are hard to change. Downside of this will be code duplication and the fact that MutableLiveDataKtx would not be subtype of LiveDataKtx anymore. I can make a pull request if you consider this as a good idea.

minSdk version 19 -> 16?

Just curious if 19 is a requirement for this lib. If not, mind lowering it to 16 to reach ~5% more people?

No worries if you'd rather not, I think I should be OK with a fork.

Thanks for the lib!

debounce() uses Handler which makes it difficult to test

The LiveData<T>.debounce(delayMillis: Long) extension relies on the Handler class, which makes view models difficult to test without Robolectric.

A possible solution is to wrap Handler with an interface and provide an API for overriding the default implementation. Something similar to RxJavaPlugins

different between versions 3.0.0 and 2.0.2

Hi

  • 1) what improvement has version 3.0.0?

  • 2) why need MutableLiveDataKtx instead MutableLiveData?

  • 3) In version 2.0 we has great extension observe without Observer

livedata.observe(this) {it ->

}

In version 3.0 observe without Observer is gone =(
We have now only ugly

.observe(lifecycleOwner, Observer { result ->

})

  • 4)

In version 2.0 I has unpleasant bug in android studio,
My breakpoint is skipped by android studio in extension observe, but code in worked

livedata.observe(this) {it ->
// here breakpoint
}

but common way work fine
.observe(lifecycleOwner, Observer { result ->
// result is non-null and always true
})

SingleLiveData doesn't work as expected

Failing test:

    @Test
    fun `single reattach`() {
        val liveData = SingleLiveData<Int>()
        val actual = mutableListOf<Int?>()
        val observer: (t: Int?) -> Unit = { actual.add(it) }
        
        liveData.observe(this, observer)
        liveData.value = 1
        liveData.removeObserver(observer)
        actual.clear()
        liveData.observe(this, observer)
        liveData.value = 2
        
        val expected = listOf(2)
        assertEquals(expected, actual) // ERROR: actual is [2, 2]
    }

The same test is passed by the original SingleLiveEvent: https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java

Common use-case that leads to this:

  1. The view is subscribed to SingleLiveData and gets an event
  2. The view is resubscribed (navigate to a different screen and come back)
  3. The next event is received twice.

Create `combineWith` operator

Create a combineWith operator as follows:

  • Should accept 2 source LiveDatas
  • Should accept a mapper function, such that f(X?, Y?) -> Z?, where X and Y are the types emitted by the sources
  • Should return a LiveData<Z?>

Supertypes of the following classes cannot be resolved.

Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:

class com.shopify.livedataktx.SupportMediatorLiveData, unresolved supertypes: androidx.lifecycle.MediatorLiveData

What is wrong?

Unnecessary Nullable types

First of all, nice work on this. I started doing something similar and came across your work.

I have some questions about some of your implementation details.

I noticed you use a nullable value in MediatorObserver:
https://github.com/henrytao-me/livedata-ktx/blob/bebbc7c3d18702d0e074e0643895d80d55d8fe29/livedata-ktx/src/main/java/me/henrytao/livedataktx/LiveData.kt#L148

I don't think this is necessary. My guess is you did this because of this line:
https://github.com/henrytao-me/livedata-ktx/blob/bebbc7c3d18702d0e074e0643895d80d55d8fe29/livedata-ktx/src/main/java/me/henrytao/livedataktx/LiveData.kt#L159

The compiler would otherwise complain because of the Observer interface function argument is annotated with @NonNull. Because this is coming from java this is needed. Seeing you are using Kotlin here we could just cast to IN (in this case). Like this:

mediator.addSource(source, Observer { observer.run(source, mediator, it as IN) })

We can do this because the type we pas in from Kotlin is already nullable so you don't have to check for non-null in the calling code.

this replaces the following:

val liveData = MutableLiveData<Int>
val mapped = liveData.map { it?.let{ it.toString() } }

with:

val liveData = MutableLiveData<Int>
val mapped = liveData.map { it.toString() }

This should still work fine if you have nullable types in Kotlin:

val liveData = MutableLiveData<Int?>
// val mapped = liveData.map { it.toString() } <-- this wouldn't work
val mapped = liveData.map { it?.let{ it.toString() } }

What's your thoughts?

Edit:
I've went a head and created a PR with these changes for you to take a look at.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.