Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue #2 #3

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,29 @@ class ProfileObservableViewModel : ObservableViewModel() {

@Bindable
fun getPopularity(): Popularity {
return likes.get().let {
when {
it > 9 -> Popularity.STAR
it > 4 -> Popularity.POPULAR
else -> Popularity.NORMAL
}
}
return likes.get().let { decidePopularity(it) }
}
}

/**
* As an alternative, the @Bindable attribute can be replaced with an
* `ObservableField`. In this case 'popularity' is an `ObservableField` which has to be computed when
* `likes` change.
*/
class ProfileObservableFieldsViewModel : ViewModel() {
val name = ObservableField("Ada")
val lastName = ObservableField("Lovelace")
val likes = ObservableInt(0)

// popularity is exposed as an ObservableField instead of a @Bindable property.
val popularity = ObservableField<Popularity>(Popularity.NORMAL)

fun onLike() {
likes.set(likes.get() + 1)

popularity.set(
likes.get().let { decidePopularity(it) }
)
}
}

Expand All @@ -92,3 +108,11 @@ enum class Popularity {
private fun ObservableInt.increment() {
set(get() + 1)
}

private fun decidePopularity(likes: Int) : Popularity {
return when {
likes > 9 -> Popularity.STAR
likes > 4 -> Popularity.POPULAR
else -> Popularity.NORMAL
}
}