I want to implement a custom list method in dart - flutter

extension MyMethod on List<int>{
void forEachCustom(void Function(int) other){
for(var e in this){
other(e);
}
}
}
void main(){
List<int> a=[1,2,3,4];
a.forEachCustom(print);
}
This just prints the elements. I want to implement my custom list method that performs operation on the original receiver on which I call the method. Example ,sort() method, that already exists,as it dosent return anything but modifies the list to which we call it

I don't know if I understand your question, but you can easily sort a list in dart with predefined method
extension MyMethod on List<int>{
void forEachCustom(void Function(int) other){
sort();
}
}

Related

Flutter, Dart. Create anonymous class

Maybe it's really dumb question. But I cannot believe there is no resources, where it's described. Even from the official documentation. What I'm trying to do, it's create Anonymous class for the next function.
How to create Anonymous class in Dart with custom function something like next in Kotlin?
Handler(Looper.getMainLooper()).post(Runnable() {
#override
open fun run() {
//...
}
private fun local() {
//....
}
})
Dart does not support creating an anonymous class.
What you're trying to do is not possible.
On the other hand, you can create anonymous functions. So you could use that to mimic an anonymous class.
The idea is to add a constructor of your abstract class, that defer its implementation to callbacks.
abstract class Event {
void run();
}
class _AnonymousEvent implements Event {
_AnonymousEvent({void run()}): _run = run;
final void Function() _run;
#override
void run() => _run();
}
Event createAnonymousEvent() {
return _AnonymousEvent(
run: () => print('run'),
);
}
It's not strictly the same as an anonymous class and is closer to the decorator pattern. But it should cover most use-cases.
This is an alternative way, but not fully equivalent:
Problem, e.g.:
I would like to implement OnChildClickListener inline in my code without class. For this method:
void setOnChildClickListener(OnChildClickListener listener) {
...
}
Instead of this:
abstract class OnChildClickListener {
bool onChildClick(int groupPosition, int childPosition);
}
use this:
typedef OnChildClickListener = Function(int groupPosition, int childPosition);
And in code you can implement it in this way:
listView.setOnChildClickListener((int groupPosition, int childPosition) {
// your code here
});
In other words do not use abstract class, but use typedef.

RxAndroid: How to add additional methods in Observer and Observable

Observer has onNext(), OnError() and onComplete().
Is there a way to add an additional method?
There is a possibility that the object received via the stream is of two types instead of the same type. And both possibilities are a success scenario. They are just handled differently by the observer.
Now, with callbacks, one would add a new method to handle this.
But not sure how this would be done with Rx.
Or is there another way of handling this without having to add a new method?
Thanks
I think the best way to achieve this is by using a common super class which can hold both objects.
In Kotlin you can do this with sealed class in Java do it with a simple POJO. One downside is that you have to use instanceOf and casting to use the actual type.
public class Result<T> {
public T result;
public Result(T result) {
this.result = result;
}
}
public class Result1 extends Result<Object1> {
public Result1(Object1 result) {
super(result);
}
}
public class Result2 extends Result<Object2> {
public Result2(Object2 result) {
super(result);
}
}
Your Observable can emit Result objects, and you can cast to either result based on what you got on the onNext method.

empty observable subscribed, but onNext not called?

I want an Observable that doesnt do anything except that when subscribed to, the observer's onNext callback is invoked. I think I found that with Observable.empty(), but the following does not result in the observer's onNext callback being invoked:
Observable<Void> emptyObservable = Observable.empty();
emptyObservable.subscribe(passedinObserver);
passedInObserver was defined:
Observer<Void> passedinObserver = new Observer<Void> {
#Override public void onCompleted() {
}
#Override public void onError(Throwable e) {
}
#Override public void onNext(Void aVoid) {
Log.d("onNext called");
}
};
You can use Observable.just(null) or any value since you are going to ingore the value anyway. However, it appears you want to perform additional work when values travel through an observable sequence, so you can use doOnNext():
Observable.range(1, 10)
.doOnNext(v -> Log.d("onNext called"))
.map(v -> v * v)
.subscribe(System.out::println);
onNext doesn't get called, onCompleted does for this type of Observable.
Alternatively to the other answers, since empty only calls onCompleted without calling onNext, maybe you just want to do your work in onCompleted rather than in onNext?
Try Observable.just(...). It will return one value and thus call .onNext(...).

RxJava (or Rx.NET) equivalent of ReactiveCocoa's RACObserve

Given an arbitrary field on a Java object, I want to create an Observable that will watch that field and push a new result to an Observer every time the value of the field changes. ReactiveCocoa has a macro called RACObserve, which appears to do exactly this.
I want to know how to implement similar functionality using RxJava.
For example, say I had the following simple class:
public class Foo {
enum State {
Idle,
Ready,
Error
}
private State currentState = State.Idle;
//methods that can change currentState
}
I want to create an Observable<State> that will push the new state to an Observer every time something changes the value of currentState.
In ReactiveCocoa, it looks like I would write something sort of like the following (please excuse my pseudo Objective-C):
[RACObserve(self, currentState) subscribeNext:^(NSString *newState) {
NSLog(#"%#", newState);
}];
How would I achieve similar functionality in RxJava? I'm thinking that I may need to wrap all changes to currentState in a setter, but it's not clear to me where I should then call Observable.create and how to feed the changes of currentState to an Observer.
ReactiveCocoa is actually more similar to ReactiveUI (http://www.reactiveui.net) than just plain Rx. And in ReactiveUI, you can use this.WhenAnyValue(x => x.PropName) to do exactly what you want.
I stumbled across this same problem recently, I ended up using PropertyChangeListener, which will emit an object when a property is changed, see the following:
Update Listener:
public class GameUpdateListener {
public static Observable<Object> changed(Game game) {
final BehaviorSubject<Object> subject = BehaviorSubject.create((Object)game);
game.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
subject.onNext( (Object)propertyChangeEvent.getNewValue());
}
});
return subject;
}
}
Some custom object:
public class Game {
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
...
public setSomeField(String field){
this.field = field;
pcs.firePropertyChange("field", this.field, field);
}
public void addPropertyChangeListener(PropertyChangeListener propertyChangeListener) {
pcs.addPropertyChangeListener(propertyChangeListener);
}
...
}
Observe:
Game game = new Game();
GameUpdateListener listener = new GameUpdateListener();
final Observable<Object> gameObserver = listener.changed(game);
gameObserver.subscribe(new Action1<Object>() {
#Override
public void call(Object o) {
Log.e(TAG, "Object Changed");
}
});
game.setSomeField("New value");
This will work fine as long as you don't need to instantiate your object again. Perhaps a solution to this is to create a local setter method and emit a change there.
Since your question title contains "or Rx.NET", here is my suggestion (I dunno bout RxJava, you may find something similar).
You probably will have to leverage some sort of mechanism in the setter. The standard way in .NET is by using the INotifyPropertyChanged interface.
Then by firing the events, you can create an IObservable<T> from this stream by using
Observable.FromEvent<TEvent, TArgs>()
You can find a really good example of what you want to do (.NET) here.
(credits to Rob Foncesa-Ensor)
I think what you are after is a Subject<T>. It implements IObserver<T>, so you can call OnNext(T) to fire a new value, as well as IObservable<T>, which you can expose it as publicly so it can be subscribed to.
If you need it to fire the latest value to new subscribers, you can use a ReplaySubject<T> with a buffer size of 1.
Here's a basic implementation:
public class SomeService
{
private Subject<int> values = new Subject<int>();
public IObservable<T> Values
{
get
{
// AsObservable prevents it from being cast back to Subject
return values.AsObservable();
}
}
// Private; called by some internal mechanism
private void SetValue(int newValue)
{
newValue.OnNext(newValue);
}
}

Static and non-static method or global class object

I'm making a Windows Forms Application in VS2012 C++.
Situation just for example, real project is more complicated:
I have a Form that contains TextBox, Button and Timer.
Button just triggers the timer. Timer just calls function that increments some variable.
I need to display the function's variable that is incremented, in TextBox.
In Form1.h I add code:
public: void Timer_Function(); //function activated by timer Tick
void Set_Text(String ^str); //function to set TextBox Text
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
if (timer1->Enabled == false) timer1->Enabled = true;
else timer1->Enabled = false;
}
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)
{
Timer_Function();
}
In My_app.cpp code like this:
#include "stdafx.h"
#include "Form1.h"
#include "resource.h"
using namespace test_staticfunc;
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Application::Run(gcnew Form1());
return 0;
}
void Form1::Timer_Function()
{
Timer_Func();
}
void Form1::Set_Text(String ^str)
{
textBox1->Text = str;
}
void Timer_Func()
{
static int I=0;
I++;
Form1::Set_Text(I.ToString());
}
Function Timer_Func() is specified in "resource.h" like this:
void Timer_Func();
I.e. I'm trying to display the current state of inner variable I of Timer_Func() by passing it to a Form1 public method Set_Text().
So. The error here is that Set_Text() is not a static method.
I tried to make it static, but got an error "ะก2227: The operand to the left of "->Text" is not a pointer to a class, structure, or union." How to get it right? In that case a static method is trying to implement a non-static method, right?
Or another way: to make an instance of Form1 - instead of
Application::Run(gcnew Form1());
insert code
Form1 ^My_form = gcnew Form1();
Application::Run(My_form);
And use Set_Text as non-static method for class instance My_form.
But My_form is available only in main()! I couldn't make My_form anywhere else. Is there way to make it global or something?
May be there are other ways to solve this problem?
Help, please! I've already searched several forums for answer but didn't find the answer. More precisely non of them suited.
P.S. Sorry for my bad english! ^_^