Last active
October 1, 2018 06:31
-
-
Save SabagRonen/f0a4e34d4c0c20cd0298aa4787a07d85 to your computer and use it in GitHub Desktop.
Why Should You Wrap LiveData With Your Own Abstraction
This file contains 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
interface ObservableViewState { | |
fun observeTitle(lifecycle: Lifecycle, observer: (String) -> Unit) | |
} | |
interface IScreenPresenter : ObservableViewState { | |
fun loadData() | |
} | |
class ScreenPresentationState : ObservableViewState { | |
private val titleLiveData = MutableLiveData<String>() | |
override fun observeTitle(lifecycle: Lifecycle, observer: (String) -> Unit) { | |
titleLiveData.observe({lifecycle}) { | |
it?.let(observer) | |
} | |
} | |
fun updateTitle(newTitle: String) { | |
titleLiveData.postValue(newTitle) | |
} | |
} | |
class ScreenPresenter( | |
private val state: ScreenPresentationState | |
) : IScreenPresenter, ObservableViewState by state { | |
override fun loadData() { | |
state.updateTitle(getSomeHowTheTitle()) | |
} | |
private fun getSomeHowTheTitle() = "this is just example" | |
} | |
class ScreenView : AppCompatActivity() { | |
@Inject lateinit var presenter: IScreenPresenter | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
presenter.observeTitle(lifecycle) { | |
// render somehow the title | |
} | |
presenter.loadData() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment