Does event wrapper pattern replace the use of SingleLiveEvent? - android

I'm adopting MVVM to my Android apps recently. In order to solve the problems underlying with the lifecycle of an app, Google had released LiveData.
The usage of LiveData has different scenarios, as pointed out in the medium article wrote by Jose Alcérreca, you can use SingleLiveEvent or something like the event wrapper pattern.
I want to make sure the SingleLiveEvent, or the event wrapper pattern, which one would be the best practice to use with LiveData in Android MVVM architecture. And I found the Google I/O app of this year(2018) have no usages of SingleLiveEvent, it uses event wrapper pattern instead.
Previously I have opened an issue on the project android-architecture, at first I'm seeking an official reply, but it seems to have no comments at all. As a result, I would like to hear the advice from the developers who already use these stuff and have reflections on it.
Please share your precious experiences, thank you in advance.

I'm not a fan of SingleLiveEvent because it restricted to one observer but you can add many observers as well, so it can be error-prone.
But in a very simple scenario(like the todo app that you mentioned), it can be a better option than event wrapper pattern.
In a complex scenario, event wrapper pattern would be a better option, but it also has some limitations. This implementation assumes you only have one main consumer (see getContentIfNotHandled). So, I think dealing with multiple observers will cause boilerplate to decide which one is the main consumer or when I should call getContentIfNotHandled or peekContent.
But, All these limitations can be fixed with your own implementation.
For example here is an extended version of SingleLiveEvent that supports multiple observers:
public class SingleLiveEvent<T> extends MutableLiveData<T> {
private LiveData<T> liveDataToObserve;
private final AtomicBoolean mPending = new AtomicBoolean(false);
public SingleLiveEvent() {
final MediatorLiveData<T> outputLiveData = new MediatorLiveData<>();
outputLiveData.addSource(this, currentValue -> {
outputLiveData.setValue(currentValue);
mPending.set(false);
});
liveDataToObserve = outputLiveData;
}
#MainThread
public void observe(#NonNull LifecycleOwner owner, #NonNull Observer<T> observer) {
liveDataToObserve.observe(owner, t -> {
if(mPending.get()) {
observer.onChanged(t);
}
});
}
#MainThread
public void setValue(T value) {
mPending.set(true);
super.setValue(value);
}
}
As you see, It's not about SingleLiveEvent vs event wrapper pattern, It all depends. Personally, I use other patterns (like patterns existing in React/Flux world) for dealing with states.
Keep in mind that there is no silver bullet in software engineering.

SingleLiveData is restricted to one observer, EventLiveData described in this article supports multiple observers.
You use it just like regular live data. No hacking or adding unnecessary complexity to code.
implementation 'com.rugovit.eventlivedata:eventlivedata:1.0'
MutableEventLiveData<String> eventLiveData =new MutableEventLiveData<>();
viewModel.event.observe(this, Observer {
// ...
})
It is extension of livedata and supports every feature of livedata.
Unlike other solutions this supports multiple observers.
Github link: https://github.com/rugovit/EventLiveData

Related

Map multiple suspend functions to single LiveData

The company I just started working at uses a so called Navigator, which I for now interpreted as a stateless ViewModel. My Navigator receives some usecases, with each contains 1 suspend function. The result of any of those usecases could end up in a single LiveData. The Navigator has no coroutine scope, so I pass the responsibility of scoping suspending to the Fragment using fetchValue().
Most current code in project has LiveData in the data layer, which I tried not to. Because of that, their livedata is linked from view to dao.
My simplified classes:
class MyFeatureNavigator(
getUrl1: getUrl1UseCase,
getUrl1: getUrl1UseCase
) {
val url = MediatorLiveData<String>()
fun goToUrl1() {
url.fetchValue { getUrl1() }
}
fun goToUrl2() {
url.fetchValue { getUrl2() }
}
fun <T> MediatorLiveData<T>.fetchValue(provideValue: suspend () -> T) {
val liveData = liveData { emit(provideValue()) }
addSource(liveData) {
removeSource(liveData)
value = it
}
}
}
class MyFeatureFragment : Fragment {
val viewModel: MyFeatureViewModel by viewModel()
val navigator: MyFeatureNavigator by inject()
fun onViewCreated() {
button.setOnClickListener { navigator.goToUrl1() }
navigator.url.observe(viewLifecycleOwner, Observer { url ->
openUrl(url)
})
}
}
My two questions:
Is fetchValue() a good way to link a suspend function to LiveData? Could it leak? Any other concerns?
My main reason to only use coroutines (and flow) in the data layer, is 'because Google said so'. What's a better reason for this? And: what's the best trade off in being consistent with the project and current good coding practices?
Is fetchValue() a good way to link a suspend function to LiveData?
Could it leak? Any other concerns?
Generally it should work. You probably should remove the previous source of the MediatorLiveData before adding new one, otherwise if you get two calls to fetchValue in a row, the first url can be slower to fetch, so it will come later and win.
I don't see any other correctness concerns, but this code is pretty complicated, creates a couple of intermediate objects and generally difficult to read.
My main reason to only use coroutines (and flow) in the data layer,
is 'because Google said so'. What's a better reason for this?
Google has provided a lot of useful extensions to use coroutines in the UI layer, e.g. take a look at this page. So obviously they encourage people to use it.
Probably you mean the recommendation to use LiveData instead of the Flow in the UI layer. That's not a strict rule and it has one reason: LiveData is a value holder, it keeps its value and provides it immediately to new subscribers without doing any work. That's particularly useful in the UI/ViewModel layer - when a configuration change happens and activity/fragment is recreated, the newly created activity/fragment uses the same view model, subscribes to the same LiveData and receives the value at no cost.
At the same time Flow is 'cold' and if you expose a flow from your view model, each reconfiguration will trigger a new flow collection and the flow will be to execute from scratch.
So e.g. if you fetch data from db or network, LiveData will just provide the last value to new subscriber and Flow will execute the costly db/network operation again.
So as I said there is no strict rule, it depends on the particular use-case. Also I find it very useful to use Flow in view models - it provides a lot of operators and makes the code clean and concise. But than I convert it to a LiveData with help of extensions like asLiveData() and expose this LiveData to the UI. This way I get best from both words - LiveData catches value between reconfigurations and Flow makes the code of view models nice and clean.
Also you can use latest StateFlow and SharedFlow often they also can help to overcome the mentioned Flow issue in the UI layer.
Back to your code, I would implement it like this:
class MyFeatureNavigator(
getUrl1: getUrl1UseCase,
getUrl1: getUrl1UseCase
) {
private val currentUseCase = MutableStateFlow<UseCase?>(null)
val url = currentUseCase.filterNotNull().mapLatest { source -> source.getData()}.asLiveData()
fun goToUrl1() {
currentUseCase.value = getUrl1
}
fun goToUrl2() {
currentUseCase.value = getUrl2
}
}
This way there are no race conditions to care about and code is clean.
And: what's the best trade off in being consistent with the project
and current good coding practices?
That's an arguable question and it should be primarily team decision. In most projects I participated we adopted this rule: when fixing bugs, doing maintenance of existing code, one should follow the same style. When doing big refactoring/implementing new features one should use latest practices adopted by the team.

Where to do Arrow.io IO.runUnsafeSync() ? ViewModel or Activity/Fragment?

I'm trying to learn the Arrow library and improve my functional programming by transitioning some of my Android Kotlin code from more imperative style to functional style. I've been doing a type of MVI programming in the application to make testing simpler.
"Traditional" Method
ViewModel
My view model has a LiveData of the view's state plus a public method to pass user interactions from the view to the viewmodel so the view model can update state in whatever way is appropriate.
class MyViewModel: ViewModel() {
val state = MutableLiveData(MyViewState()) // MyViewState is a data class with relevant data
fun instruct(intent: MyIntent) { // MyIntent is a sealed class of data classes representing user interactions
return when(intent) {
is FirstIntent -> return viewModelScope.launch(Dispatchers.IO) {
val result = myRoomRepository.suspendFunctionManipulatingDatabase(intent.myVal)
updateStateWithResult(result)
}.run { Unit }
is SecondIntent -> return updateStateWithResult(intent.myVal)
}
}
}
Activity
The Activity subscribes to the LiveData and, on changes to state, it runs a render function using the state. The activity also passes user interactions to the view model as intents (not to be confused with Android's Intent class).
class MyActivity: AppCompatActivity() {
private val viewModel = MyViewModel()
override fun onCreateView() {
viewModel.state.observe(this, Observer { render(it) })
myWidget.onClickObserver = {
viewModel.instruct(someIntent)
}
}
private fun render(state: MyViewState) { /* update view with state */ }
}
Arrow.IO Functional Programming
I'm having trouble finding examples that aren't way over my head using Arrow's IO monad to make impure functions with side effects obvious and unit-testable.
View Model
So far I have turned my view model into:
class MyViewModel: ViewModel() {
// ...
fun instruct(intent: MyIntent): IO<Unit> {
return when(intent) {
is FirstIntent -> IO.fx {
val (result) = effect { myRoomRepository.suspendFunctionManipulatingDatabase(intent.myVal) }
updateStateWithResult(result)
}
is SecondIntent -> IO { updateStateWithResult(intent.myVal) }
}
}
}
I do not know how I am supposed to make this IO stuff run in Dispatcher.IO like I've been doing with viewModelScope.launch. I can't find an example for how to do this with Arrow. The ones that make API calls all seem to be something other than Android apps, so there is no guidance about Android UI vs IO threads.
View model unit test
Now, because one benefit I'm seeing to this is that when I write my view model's unit tests, I can have a test. If I mock the repository in order to check whether suspendFunctionManipulatingDatabase is called with the expected parameter.
#Test
fun myTest() {
val result: IO<Unit> = viewModel.instruct(someIntent)
result.unsafeRunSync()
// verify suspendFunctionManipulatingDatabase argument was as expected
}
Activity
I do not know how to incorporate the above into my Activity.
class MyActivity: AppCompatActivity() {
private val viewModel = MyViewModel()
override fun onCreateView() {
viewModel.state.observe(this, Observer { render(it) })
myWidget.onClickObserver = {
viewModel.instruct(someIntent).unsafeRunSync() // Is this how I should do it?
}
}
// ...
}
My understanding is anything in an IO block does not run right away (i.e., it's lazy). You have to call attempt() or unsafeRunSync() to get the contents to be evaluated.
Calling viewModel.instruct from Activity means I need to create some scope and invoke in Dispatchers.IO right? Is this Bad(TM)? I was able to confine coroutines completely to the view model using the "traditional" method.
Where do I incorporate Dispatchers.IO to replicate what I did with viewModelScope.launch(Dispatchers.IO)?
Is this the way you're supposed to structure a unit test when using Arrow's IO?
That's a really good post to read indeed. I'd also recommend digging into this sample app I wrote that is using ArrowFx also.
https://github.com/JorgeCastilloPrz/ArrowAndroidSamples
Note how we build the complete program using fx and returning Kind at all levels in our architecture. That makes the code polymorphic to the type F, so you can run it using different runtime data types for F at will, depending on the environment. In this case we end up running it using IO at the edges. That's the activity in this case, but could also be the application class or a fragment. Think about this as what'd be the entry points to your apps. If we were talking about jvm programs the equivalent would be main(). This is just an example of how to write polymorphic programs, but you could use IO.fx instead and return IO everywhere, if you want to stay simpler.
Note how we use continueOn() in the data source inside the fx block to leave and come back to the main thread. Coroutine context changes are explicit in ArrowFx, so the computation jumps to the passed thread right after the continueOn until you deliberately switch again to a different one. That intentionally makes thread changes explicit.
You could inject those dispatchers to use different ones in tests. Hopefully I can provide examples of this soon in the repo, but you can probably imagine how this would look.
For the syntax on how to write tests note that your program will return Kind (if you go polymorphic) or IO, so you would unsafeRunSync it from tests (vs unsafeRunAsync or unsafeRunAsyncCancellable in production code since Android needs it to be asynchronous). That is because we want our test to be synchronous and also blocking (for the latter we need to inject the proper dispatchers).
Current caveats: The solution proposed in the repo still doesn't care of cancellation, lifecycle or surviving config changes. That's something I'd like to address soon. Using ViewModels with a hybrid style might have a chance. This is Android so I'd not fear hybrid styles if that brings better productivity. Another alternative I've got in mind would maybe be something a bit more functional. ViewModels end up retaining themselves using the retain config state existing APIs under the hood by using the ViewModelStore. That ultimately sounds like a simple cache that is definitely a side effect and could be implemented wrapped into IO. I want to give a thought to this.
I would definitely also recommend reading the complete ArrowFx docs for better understanding: https://arrow-kt.io/docs/fx/ I think it would be helpful.
For more thoughts on approaches using Functional Programming and Arrow to Android you can take a look to my blog https://jorgecastillo.dev/ my plan is to write deep content around this starting 2020, since there's a lot of people interested.
In the other hand, you can find me or any other Arrow team maintainers in the Kotlinlang JetBrains Slack, where we could have more detailed conversations or try to resolve any doubts you can have https://kotlinlang.slack.com/
As a final clarification: Functional Programming is just a paradigm that resolves generic concerns like asynchrony, threading, concurrency, dependency injection, error handling, etc. Those problems can be found on any program, regardless of the platform. Even within an Android app. That is why FP is an option as valid for mobile as any other one, but we are still into explorations to provide the best APIs to fulfill the usual Android needs in a more ergonomic way. We are in the process of exploration in this sense, and 2020 is going to be a very promising year.
Hopefully this helped! Your thoughts seem to be well aligned with how things should work in this approach overall.

Android, Do I use ViewModel to perform insertion or update?

I understand that ViewModel in the Architecture component is for storage and managing data so it will not be lost during config changes.
For example, my activity has nothing do with LiveData or using storage Data. Should I still go through ViewModel? or directly instantiate the Repo Class and call the insertion method? I hope that make sense
An Example of my usage of ViewModel
public class MainViewModel extends AndroidViewModel {
private DataRepo dataRepo;
private LiveData<List<Group>> groupList;
private LiveData<List<Bill>> billList;
public MainViewModel(Application application) {
super(application);
dataRepo = new DataRepo(this.getApplication));
groupList = dataRepo.getGroup();
billList = dataRepo.getBill();
}
public LiveData<List<Group>> getGroupList() {
return groupList:
}
public LiveData<List<Bill>> getBillList() {
return billList:
}
public void insertGroupAndMember(Group group) {
dataRepo.insertGroupAndMember(group);
}
public void insertBills(List<Bill> bills) {
dataRepo.insertBills(bills);
}
public List<Member> getMemberList(Group group) {
return dataRepo.getMembers(group);
}
}
I think you want to use a ViewModel to keep your UI controller as clean as possible. Your viewmodel should call the repo to do simple CRUD operations.
See below snippet from documentation:
Requiring UI controllers
to also be responsible for loading data from a database or network
adds bloat to the class. Assigning excessive responsibility to UI
controllers can result in a single class that tries to handle all of
an app's work by itself, instead of delegating work to other classes.
Assigning excessive responsibility to the UI controllers in this way
also makes testing a lot harder.
Here are some points I would advice you to consider:
MVVM as a pattern has it's roots back in 2000-th, for example, here is Martin Fowler's article about the concept, and in 2005 John Gossman announced the pattern in his blog. Yes, it solves the problem with rotation in android's implementation of the pattern, but this problem could be solved without it. MVVM is actualy needen for separation of presentation state from views that are seen to the end user. As Wiki says -
The view model is an abstraction of the view exposing public properties and commands. Instead of the controller of the MVC pattern, or the presenter of the MVP pattern, MVVM has a binder, which automates communication between the view and its bound properties in the view model. The view model has been described as a state of the data in the model.
So, primarily it is (like all other GUI architectural patterns in their root) about abstraction between view and domain parts of the application, so that they can vary independently and subsequent changes to the system will be cheap.
Instantiating domain objects in the view scope and their subsequent use by the view leads to tight coupling between the view and domain objects, which is a bad characteristic of any system. Also, it is one more reason to change view's internals, because if construction logic of the domain object changes - view will have to be changed too.
If ViewModel is exessive for you (as I can see, its benefits are not relevant for you in this particular case, because the UI is not very complex and it's state is lightweight), consider using a less heavy-weight abstraction, such as MVP. Thus, you will be able to preserve abstraction between view and model in your application (no unwanted coupling) and you won't have to support the code that you don't benefit from.

Observable transformers made of Subjects

I am currently implementing a pattern that has a view-viewmodel circular dependency. Though its really not dependency because they don't know about each other, all they know is that there is a stream of events and a stream of states. I came up with an idea of making the viewModel implement a function called toTransformer() which returns an ObservableTransformer that's composed of two subjects, an event subject and a state subject.
private val eventStream: PublishSubject<MainEvent> = PublishSubject.create()
private val stateSink: BehaviorSubject<MainState> = BehaviorSubject.create()
...
fun asTransformer(): ObservableTransformer<MainEvent, MainState> =
ObservableTransformer {
it.subscribe { eventStream.onNext(it) }
stateSink
}
And is used like this
view.events().compose(viewModel.asTransformer()).subscribe { view.render(it) }
Questions
Is it okay to do this?
What could go wrong with this implementation.
Will the inner subscription be disposed if the subscription is disposed?
Can this be improved to a better form?
Edit
This is how event and state relates.
eventStream.map { it.toAction() }
.compose(actionToResult())
.scan (MainState.initial(), reducer())
.subscribe {
stateSink.onNext(it)
}
I don't know if you based it off of this, but Jake Wharton has a great presentation on this kind of architecture.
Is it okay to do this?
In general, sure.
What could go wrong with this implementation.
One thing you probably want to be careful of is that you essentially have one big event loop. If your event loop dies, the UI will be non-responsive. Correct error handling is even more important than before. I'm sure your code snippets above are a simplified version of what you really have, but consider that without an error handling block, failures in your inner subscription will bubble up to your outer subscription which will itself fail. At this point, there will be no active subscriptions to UI events.
Will the inner subscription be disposed if the subscription is disposed?
No. It's not in the same chain.
Can this be improved to a better form?
Especially in consideration of the previous answer, you may want to get rid of the inner subscription so that it's all one chain. An easy way is to use flatMap instead of subscribing.

Android MVP and framework specific code

I was reading an article by Dario Miličić regarding MVP here. I also thoroughly went through the code he provided on git hub. Anyways, i am pretty new to MVP for android and MVP in general, and so I have a question about what he said - "The implementation layer is where everything framework specific happens”. What if i have an android application that deals with Bluetooth? i.e. i have a small application to get a list of bluetooth devices using BluetoothAdapter which is an android class. So I started writing a use cases which was something like this
public interface BluetoothScanInteracotor {
interface View {
void onScanStarted();
void onScanCompleted();
}
void scanForDevices();
}
but then realised that I cant do that because of its framework specific.
How would I go about this?
Forgive me if that's a silly question, but I might be confused about something and I need someone to help me understand.
The CLEAN approach would be to implement a BluetoothDeviceRepository, which could have multiple implementations, one of which would actually access the system resources, but could easily be swapped for one with no external dependencies for test, etc. The Bluetooth device scan results would be converted by repository implementations to return POJO models that represented the information you needed, so that there would be no leakage of the Android system classes into this layer.
The issue with most MVP implementation out there is that they designate Activities and Fragments as Views, and propose to use "Android framework independent" presenters.
This sounds good until one encounters issues like yours - Bluetooth framework is part of Android framework, so it is not clear how to use it in the presenter that shouldn't depend on Android specific classes.
After researching MVx architectures on Android for several years I realized that the only sane conclusion that can be derived is that Activities and Fragments are not views, but presenters.
The more detailed discussion of this subject can be found here: Why Activities in Android are not UI Elements.
Based on this idea I proposed an alternative implementation of MVP in Android: MVP and MVC Architectures in Android.
I have an idea in MVP model that not bad to share with you,
Everything that depends on the OS,should be treated as View, and Logic is Presenter,
For example Activity is a View, we use it to intract with UI ,for example get Text of a Textview, and when we need to process on the text, we make a presenter class for this activity and also an interface to this presenter, then implement the interface in presenter,and call methods of interface in Activity with needed params(for example that Text)
If I want implement it in another OS, i should only change my Activity and get Text in other way,and remain process is same and doesn't change
As you have come to know basics of Clean Architechure. The following example depicts how actual your MVP pattern is implemented.
Example:
interface BaseContract {
interface BaseView {
//Methods for View
void onDoSomething();
}
interface BasePresenter {
void doSomething();
}
}
class BaseMainPresenter implements BaseContract.BasePresenter {
BaseContract.BaseView view;
BaseMainPresenter(BaseContract.BaseView view) {
this.view = view;
}
#Override
public void doSomething() {
if (view != null)
view.onDoSomething();
}
}
class DemoClass implements BaseContract.BaseView {
//Create object of Presenter
/****
* Example :
* BaseMainPresenter baseMainPresenter = new BaseMainPresenter(this);
*/
#Override
public void onDoSomething() {
//Deal with Context here.
}
}

Categories

Resources