RXJava Observable emit items when subscribe with Observer as anonymous type ONLY - rx-java2

When I create a new Observer as anonymous type It works Fine:
Observable<List<Post>> postsListObservable = mApplicationAPI.getPosts();
postsListObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).subscribe( new Observer<List<Post>>() {
#Override
public void onSubscribe(Disposable d) {
Log.i("ZOKa", "onSubscribe: ");
}
#Override
public void onNext(List<Post> posts) {
Log.i("ZOKa", "onNext: " + posts.size());
}
#Override
public void onError(Throwable e) {
Log.i("ZOKa", "onError: " + e.getMessage());
}
#Override
public void onComplete() {
Log.i("ZOKa", "onComplete: ");
}
});
When I create the Observer as a Dynamic Type it doesn't emit data
Observable<List<Post>> postsListObservable = mApplicationAPI.getPosts();
postsListObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread());
Observer<List<Post>> observer = new Observer<List<Post>>() {
#Override
public void onSubscribe(Disposable d) {
Log.i("ZOKa", "onSubscribe: ");
}
#Override
public void onNext(List<Post> posts) {
Log.i("ZOKa", "onNext: " + posts.size());
}
#Override
public void onError(Throwable e) {
Log.i("ZOKa", "onError: " + e.getMessage());
}
#Override
public void onComplete() {
Log.i("ZOKa", "onComplete: ");
}
};
postsListObservable.subscribe(observer);
Logcat for the first code snippet:
com.tripleService.basesetupfordi/I/ZOKa: onSubscribe:
com.tripleService.basesetupfordi/I/ZOKa: onNext: 100:
com.tripleService.basesetupfordi/I/ZOKa: onComplete:
Logcat for the second one:
com.tripleService.basesetupfordi/I/ZOKa: onError: null
So, What is the diff in between?

That's because Operators return new observables, but they don't modify the observable that they were called on. subscribeOn and observeOn in the second example has no impact on the postsListObservable and the observer.
Following should work:
Observable<List<Post>> postsListObservable = mApplicationAPI.getPosts();
Observable<List<Post>> postsListObservable2 = postsListObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread());
Observer<List<Post>> observer = new Observer<List<Post>>() {
...
};
postsListObservable2.subscribe(observer);
or
Observable<List<Post>> postsListObservable = mApplicationAPI.getPosts();
Observer<List<Post>> observer = new Observer<List<Post>>() {
...
};
postsListObservable.
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).subscribe(observer);

Related

RxJava adjust backpressure avoiding observeOn buffer

In the code below I would like the subscriber to control when the Flowable emits an event by holding a reference to the Subscription inside subscribe() and requesting the number of elements I want to be produced.
What I am experiencing is that observeOn()'s buffer with size 2 is hiding my call to subscription.request(3) as the producer is producing 2 elements at a time instead of 3.
public class FlowableExamples {
public static void main(String[] args) throws InterruptedException {
long start = new Date().getTime();
Flowable<Integer> flowable = Flowable
.generate(() -> 0, (Integer state, Emitter<Integer> emitter) -> {
int newValue = state + 1;
log("Producing: " + newValue);
emitter.onNext(newValue);
return newValue;
})
.take(30);
flowable
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation(), false, 2)
.subscribe(new Subscriber<Integer>() {
Subscription subscription;
#Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(5);
}
#Override
public void onNext(Integer integer) {
log("\t\treceived: " + integer);
if (integer >= 5) {
sleep(500);
log("Requesting 3 should produce 3, but actually produced 2");
subscription.request(3);
sleep(1000);
}
}
#Override
public void onError(Throwable throwable) {}
#Override
public void onComplete() {
log("Subscription Completed!!!!!!!!");
}
});
sleep(40_000);
System.out.println("Exit main after: " + (new Date().getTime() - start) + " ms");
}
private static void log(String msg) {
System.out.println(Thread.currentThread().getName() + ": " + msg);
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {}
}
}
How could I accomplish this?

runOnUiThread not working properly

I am trying to create textview in android which display the remaining time(seconds).
Have used runOnUiThread and Hadnler for this and everything seems working fine(sysout and debug shows that both threads are executed and value is updated properly).
However, on UI the textview value is not updated properly. It gets updated with last value when the thread completes.
I am writing the below code inside private method of the fragment.
final TextView timerText = (TextView) mainView.findViewById(R.id.timerText);
timerText.setText(R.string.maxAllowedSeconds);
handler.post(new Runnable() {
#Override
public void run() {
while(true)
{
System.out.println("Text:"+ ""+maxAllowedSeconds);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
maxAllowedSeconds--;
if(maxAllowedSeconds <= 0)
break;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("Running on UI Thread : " + maxAllowedSeconds);
timerText.setText("" + maxAllowedSeconds);
}
});
}
}
});
Gone through many of the previous questions in this area but none seems to have concrete solutions for this problem.
Thanks in advance.
SOLUTOIN:
Finally I used AsynchTask which worked perfectly as expected.
private class RapidFireAsyncTimerTask extends AsyncTask<Integer, Integer, Void> {
private Context context;
private View rootView;
public RapidFireAsyncTimerTask(Context ctx, View rootView) {
this.context = ctx;
this.rootView = rootView;
}
#Override
protected Void doInBackground(Integer... params) {
int maxSec= params[0];
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(--maxSec);
if (maxSec <= 0)
break;
}
return null;
}
#Override
protected void onProgressUpdate(final Integer... values) {
((TextView) rootView.findViewById(R.id.timerText)).setText("" + values[0]);
}
#Override
protected void onPostExecute(Void aVoid) {
//next task
}
}
Instead of Handler, it worked with AsynchTask(No runOnUiThread needed).
public RapidFireAsyncTimerTask(Context ctx, View rootView) {
this.context = ctx;
this.rootView = rootView;
}
#Override
protected Void doInBackground(Integer... params) {
int maxSec= params[0];
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(--maxSec);
if (maxSec <= 0)
break;
}
return null;
}
#Override
protected void onProgressUpdate(final Integer... values) {
((TextView) rootView.findViewById(R.id.timerText)).setText("" + values[0]);
}
#Override
protected void onPostExecute(Void aVoid) {
//next task
}
}

Why does setText in the TextField doesn't work?

Why does this method doesn't save the new selected categories. is there something wrong with my codes?
catCon = new TextField();
rowEditing.addEditor(catConfig, catCon);
this is the code for setting the catCon:
TextButton save = new TextButton("Save");
save.addSelectHandler(new SelectEvent.SelectHandler() {
#Override
public void onSelect(SelectEvent event) {
selectedItems = new LinkedList<Short>();
for (int i = 0; i < toCat.size(); i++) {
selectedItems.add(toCat.get(i).getIDCategory());
}
Collections.sort(selectedItems);
newSelectedItems = selectedItems.toString().replace(",", "-").replace("[", "").replace("]", "").replace(" ", "");
msg = new MessageBox("SELECTED ITEMSSSSSSSSS: " + selectedItems.size() + " " + newSelectedItems);;
msg.show();
catCon.setText(newSelectedItems);
hide();
}
});
and this is where the saving of the commited changes:
rowEditing.getSaveButton().addSelectHandler(new SelectEvent.SelectHandler() {
#Override
public void onSelect(SelectEvent event) {
store.commitChanges();
service.saveUserRights(store.get(index), new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable caught) {
msg = new MessageBox("Error", caught.getMessage());
msg.show();
}
#Override
public void onSuccess(Boolean result) {
if (result) {
msg = new MessageBox("Information", "Changes saved.");
msg.show();
service.getURListGrid(new AsyncCallback<List<UserRights>>() {
#Override
public void onFailure(Throwable caught) {
MessageBox msg = new MessageBox("Error", caught.getMessage());
msg.show();
}
#Override
public void onSuccess(List<UserRights> result) {
store = new ListStore<UserRights>(properties.idRight());
store.addAll(result);
grid.reconfigure(store, cm);
}
});
} else {
msg = new MessageBox("Error", "Failed to save changes.");
msg.show();
}
}
});
}
});
When I am going to set the catCon there will no be changes of the data but when I manually type the categories there will be a change. Can somebody help me?
In order for me to save the current categories is to get the index of the store and set the category to the newSelectedItem
store.get(index).setCategories(newSelectedItems);
I hope this will help to the people who has the same problem as mine.

how to get the typing status in asmack android [duplicate]

I am developing chat application by using Openfire XMPP server. I can text chat between two user. But i want to know Typing status when some one is typing message. So i created a class :-
public class typingStatus implements ChatStateListener {
#Override
public void processMessage(Chat arg0, Message arg1) {
// TODO Auto-generated method stub
}
#Override
public void stateChanged(Chat arg0, ChatState arg1) {
// TODO Auto-generated method stub
System.out.println(arg0.getParticipant() + " is " + arg1.name());
}
}
But i am confuse so that How will it work? I know that i need a packet where i can it in Listener. But i am unable to find that packet.
Please any one suggest, How will it work?
and also what is difference between Smack and asmack?
Thank you!
To enable ChatStateListener you need to create a custom MessageListener Class
public class MessageListenerImpl implements MessageListener,ChatStateListener {
#Override
public void processMessage(Chat arg0, Message arg1) {
System.out.println("Received message: " + arg1);
}
#Override
public void stateChanged(Chat arg0, ChatState arg1) {
if (ChatState.composing.equals(arg1)) {
Log.d("Chat State",arg0.getParticipant() + " is typing..");
} else if (ChatState.gone.equals(arg1)) {
Log.d("Chat State",arg0.getParticipant() + " has left the conversation.");
} else {
Log.d("Chat State",arg0.getParticipant() + ": " + arg1.name());
}
}
}
Then you create MessageListener object
MessageListener messageListener = new MessageListenerImpl();
And then pass this in the create chat method
Chat newChat = chatmanager.createChat(jabber_id_of_friend, messageListener);
what is difference between Smack and asmack? <-- Check This
finally I got the solution. I need to use chat listener along with chat manager and also I need to use in built sendcomposingnotification function. No need to use Messageeventrequestlistener interface or any other custom class for this. I added the following lines,,
connection.getChatManager().addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(final Chat arg0, final boolean arg1) {
// TODO Auto-generated method stub
arg0.addMessageListener(new MessageListener()
{
#Override
public void processMessage(Chat arg0, Message arg1)
{
// TODO Auto-generated method stub
Log.d("TYpe Stat",title[0] + " is typing......");
Toast.makeText(getApplicationContext(),title[0] + " is typing......",Toast.LENGTH_SHORT).show();
}
}
});
}
});
and also need to send notification like this..
mem.sendComposingNotification(etRecipient.getText().toString(), message.getPacketID());
System.out.println("Sending notification");
where mem is type of MessageEventManger.
Ref: http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware/smackx/MessageEventManager.html
ChatManager chatManager = ChatManager.getInstanceFor(connection);
Chat chat= chatManager.createChat(to, new ChatStateListener() {
#Override
public void stateChanged(Chat chat, ChatState state) {
switch (state){
case active:
Log.d("state","active");
break;
case composing:
Log.d("state","composing");
break;
case paused:
Log.d("state","paused");
break;
case inactive:
Log.d("state","inactive");
break;
case gone:
Log.d("state","gone");
break;
}
}
#Override
public void processMessage(Chat chat, Message message) {
Log.d("processMessage","processMessage");
}
});
use this code.hope so will work
i am using chat state listener :
Chat chat = chatManager.createChat(jid,
new ChatStateChangedListener());
bind the chatstatelistener with each jid like above , then :
public class ChatStateChangedListener implements ChatStateListener {
public ChatStateChangedListener() {
printLog("Chat State Changed Listner Constructor");
}
#Override
public void processMessage(Chat arg0, Message arg1) {
}
#Override
public void stateChanged(Chat chat, ChatState state) {
if (state.toString().equals(ChatState.composing.toString())) {
tvLastSeen.setText("Typing...");
} else if (state.toString().equals(ChatState.paused.toString())) {
tvLastSeen.setText("paused...");
} else {
tvLastSeen.setText("nothing");
}
}
}
}
Create On Class MMessageListener to listen incoming messages
private class MMessageListener implements MessageListener, ChatStateListener {
public MMessageListener(Context contxt) {
}
#Override
public void stateChanged(Chat chat, ChatState chatState) {
mStatus = "Online";
if (ChatState.composing.equals(chatState)) {
mStatus = chat.getParticipant() + " is typing..";
Log.d("Chat State", chat.getParticipant() + " is typing..");
} else if (ChatState.gone.equals(chatState)) {
Log.d("Chat State", chat.getParticipant() + " has left the conversation.");
mStatus = chat.getParticipant() + " has left the conversation.";
} else if (ChatState.paused.equals(chatState)){
Log.d("Chat State", chat.getParticipant() + ": " + chatState.name());
mStatus = "Paused";
}else if (ChatState.active.equals(chatState)){
mStatus = "Online";
}
// do whatever you want to do once you receive status
}
#Override
public void processMessage(Message message) {
}
#Override
public void processMessage(Chat chat, Message message) {
}
}
Add Listener to your chat object
Chat Mychat = ChatManager.getInstanceFor(connection).createChat(
"user2#localhost"),
mMessageListener);
Send status to receiving user on edittext text change
ChatStateManager.getInstance(connection).setCurrentState(ChatState.composing, Mychat);
This works fine for me.
Your or another xmpp client which you use, should sending chat state for You can catch the state.
Like This;
try {
ChatStateManager.getInstance(GlobalVariables.xmppManager.connection).setCurrentState(ChatState.composing, chat);
} catch (XMPPException e) {
e.printStackTrace();
}
or
try {
ChatStateManager.getInstance(GlobalVariables.xmppManager.connection).setCurrentState(ChatState.gone, chat);
} catch (XMPPException e) {
e.printStackTrace();
}
However you can get it from ProcessPacket also.
there you will get a Message object, after you can extract xml portion from there and handle them its contain specific chatstate or not.
Message message = (Message) packet;
String msg_xml = message.toXML().toString();
if (msg_xml.contains(ChatState.composing.toString())) {
//handle is-typing, probably some indication on screen
} else if (msg_xml.contains(ChatState.paused.toString())) {
// handle "stopped typing"
} else {
// normal msg
}
now handle as per your requirement.
Just add ChatStateManager after ChatManager intalization:
chatManager = ChatManager.getInstanceFor(getXmpptcpConnection());
ChatStateManager.getInstance(getXmpptcpConnection());
Then you need to add ChatStateListener during createChat(to,chatMesageListener):
chatManager.createChat(message.getTo(), chatMessageListener).sendMessage(message);
private ChatStateListener chatMessageListener = new ChatStateListener() {
#Override
public void stateChanged(Chat chat, ChatState state) {
//State Change composing,active,paused,gone,etc
Log.d(TAG, "ChatStateListener:::stateChanged -> " + chat.toString() + " \n -> " + state.toString());
}
#Override
public void processMessage(Chat chat, Message message) {
//Incoming Message
Log.d(TAG, "ChatStateListener:::processMessage -> " + chat.toString() + " \n -> " + message.toString());
}
};

Netbeans QuickSearch Result to Lookup

Well, I'd like to provide QuickSearch result inside application, and, of course, through the lookup.
Searching works well, but found result is not visible through global lookup.
Can someone help to overcome this issue ?
Here is th code for a quicksearch :
public class QSERSCompany implements SearchProvider {
#Override
public void evaluate(SearchRequest request, SearchResponse response) {
try {
for (Company k : queries.ERSQuery.allCompanies()) {
if (k.getCompanyName().toLowerCase().contains(request.getText().toLowerCase())) {
if (!response.addResult(new SearchResult(k), k.getCompanyName())) {
return;
}
}
}
} catch (NullPointerException npe) {
}
}
private static class SearchResult implements Runnable, Lookup.Provider {
private final Company company;
private final InstanceContent ic = new InstanceContent();
private final Lookup lookup = new AbstractLookup(ic);
public SearchResult(Company c) {
this.company= c;
}
#Override
public void run() {
ic.add(company);
try {
StatusDisplayer.getDefault().setStatusText(
company.getCompanyName()
+ ", " + company.getAddress()
+ ", " + company.getCity());
} catch (NullPointerException npe) {
}
}
#Override
public Lookup getLookup() {
return lookup;
}
}
}
And this is partof the code which listens for a Company object :
public final class ManagementPodatakaTopComponent extends TopComponent {
private Lookup.Result<Company> companyLookup = null;
...
private Company selectedCompany;
...
#Override
public void componentOpened() {
companyLookup = Utilities.actionsGlobalContext().lookupResult(Company.class);
companyLookup .addLookupListener(new LookupListener() {
#Override
public void resultChanged(LookupEvent le) {
Lookup.Result k = (Lookup.Result) le.getSource();
Collection<Company> cs = k.allInstances();
for (Company k1 : cs) {
selectedCompany = k1;
}
setCompanyTextFields(selectedCompany);
jTP_DataManagement.setVisible(true);
jPanel_Entiteti.setVisible(true);
}
});
}
A SearchResult which provides a lookup? Never seen this in the wild.
Please ask at nbdev#netbeans.org to get better feedback (probably from one of the NB devs)
I finally managed somehow to get what I want :
First off, define interface:
public interface ICodes {
public Code getCode();
}
Then, we implement quick search :
#ServiceProvider(service = ICodes.class)
public class ClientServicesQS implements SearchProvider, ICodes {
private static Code code = null;
#Override
public void evaluate(SearchRequest request, SearchResponse response) {
try {
for (Code c : INFSYS.queries.INFSistemQuery.ByersByName(request.getText())) {
if (!response.addResult(new SearchResult(c),
c.getName() + " ,Code: " + c.getByerCode()
+ (c.getAddress() != null ? ", " + c.getAddress() : ""))) {
return;
}
}
} catch (NullPointerException npe) {
StatusDisplayer.getDefault().setStatusText("Error." + npe.getMessage());
}
}
#Override
public Code getCode() {
return ClientServicesQS.sifra;
}
private static class SearchResult implements Runnable {
private final Code code;
public SearchResult(Code code) {
this.code= code;
}
#Override
public void run() {
try {
ClientServicesQS.code= this.code;
OpenTopComponent("ClientServicesTopComponent");
} catch (NullPointerException e) {
Display.messageBaloon("Error.", e.toString() + ", " + e.getMessage(), Display.TYPE_MESSAGE.ERROR);
}
}
}
}
Finally, we implement lookup in other module through platform.
Because I want to call lookup whenever componentOpen, oe componentActivated is invoked, it is usefull first to define :
private void QSCodeSearch() {
try {
ICode ic= Lookup.getDefault().lookup(ICode.class);
if ((code = ic.getCode()) != null) {
.
.
.
// setup UI components with data from lookup
.
.
.
}
} catch (Exception e) {
}
}
And when topcomponent is activated, we call QSCodeSearch() in :
#Override
public void componentOpened() {
...
QSCodeSearch()
...
}
...
#Override
public void requestActive() {
...
QSCodeSearch()
...
}