[Question] Simulate DomEventStream click on page load #108
Replies: 7 comments 6 replies
-
If I understand your challenge correctly, here's what I'd do: val requestStream = EventStream.merge(
EventStream.fromValue(()), // emit a Unit event initially
refreshClickStream.mapToUnit // then emit all events from the refreshClickStream stream (mapped to Unit)
).map {
_ =>
println("get url")
val randomOffset = Math.floor(Math.random()*500)
s"$githubUrl?since=$randomOffset"
} |
Beta Was this translation helpful? Give feedback.
-
Observables are (kinda) declarative, that is, you need to specify their behaviour when you're creating them. When you create a DomEventStream, you tell it which element to look at, and what event type ("click") to listen to. You can call .click() on that element to simulate the click event and kinda "fool" the observable into thinking the user actually clicked it, but that is a special method provided by the browser. So, you can't cause DomEventStream to emit events that aren't clicks, but you can create another stream that will merge your DomEventStream with some other stream. Yurique above showed how to merge your There are several ways to create a stream that lets you fire events imperatively, whenever you please – they're listed here among some other useful stream types. For example, you could create a stream from scratch using That way, instead of faking a click, you're properly declaring your dataflow, creating a stream that depends not only on clicks but also on your other logic that is needed to produce the desired results. PS I see you're using Airstream without Laminar – this is certainly possible, but is more manual and more cumbersome because you need to manage ownership lifecycles yourself. If you get bogged down with ownership, just know that it's much smoother with Laminar. |
Beta Was this translation helpful? Give feedback.
-
Hi, @raquo thanks, that worked!. @raquo This isn't real work, it's just a study on FPS. I'm trying to reproduce this using AirStream https://gist.github.com/staltz/868e7e9bc2a7b8c1f754. For real projects I'm already using Laminar. |
Beta Was this translation helpful? Give feedback.
-
I wonder if we should convert this into a Discussion, for posterity :) |
Beta Was this translation helpful? Give feedback.
-
Of course, it would be great. I'll finish porting the example from RxJS to Scala/AirStream and post the complete code. By the way, how do I make this code run only once? When I connect val refreshButton = document.querySelector(".refresh").asInstanceOf[HTMLButtonElement]
val refreshClickStream = EventStream.merge(
DomEventStream[dom.MouseEvent](refreshButton, "click").mapToUnit,
EventStream.fromValue(())
)
val closeButton = document.querySelector(".close1").asInstanceOf[HTMLButtonElement]
val closeClickStream = EventStream.merge(
DomEventStream[dom.MouseEvent](closeButton, "click").mapToUnit,
EventStream.fromValue(())
)
val requestUrlStream = refreshClickStream.map(_ => githubUrl)
val responseStream = requestUrlStream.flatMap {
url =>
FetchStream
.get(url)
.map(_.length)
}
val combinedStream = closeClickStream.combineWithFn(responseStream) {
(x, y) => s"combined result x=${x}, y=${y}"
}
combinedStream.addObserver(Observer{
s => println(s)
}) this code show |
Beta Was this translation helpful? Give feedback.
-
The RxJS has a convenient from val closeClickStream = EventStream.merge(
DomEventStream[dom.MouseEvent](closeButton, "click").mapToUnit,
EventStream.fromValue(())
) to val closeClickStream =
DomEventStream[dom.MouseEvent](closeButton, "click")
.mapToUnit
.startsWith(())
That seems clean. If I use a |
Beta Was this translation helpful? Give feedback.
-
the port to scalajs is done; Code: case class User(id: Int,
login: String,
url: String,
avatar_url: String
) derives NativeConverter
private val dynOwner = new DynamicOwner(() => ())
private val dynSub = DynamicSubscription.unsafe(
dynOwner,
activate = (owner: Owner) =>
given o: Owner = owner
appStart()
)
def createButtonClickStream(selector: String) =
val btn = document.querySelector(selector).asInstanceOf[HTMLLinkElement]
EventStream.merge(
EventStream.fromValue(()),
DomEventStream[MouseEvent](btn, "click").mapToUnit,
)
def renderSuggestion(user: Option[User], selector: String): Unit =
val el = document.querySelector(selector).asInstanceOf[HTMLUListElement]
if user.isEmpty then
el.style.visibility = "hidden"
else
val u = user.get
el.style.visibility = "visible"
val usernameEl = el.querySelector(".username").asInstanceOf[HTMLLinkElement]
val imgEl = el.querySelector("img").asInstanceOf[HTMLImageElement]
usernameEl.href = u.url
usernameEl.textContent = u.login
imgEl.src = ""
imgEl.src = u.avatar_url
def appStart()(using owner: Owner) =
val githubUrl = "https://api.github.com/users"
val refreshClickStream = createButtonClickStream(".refresh")
val close1ClickStream = createButtonClickStream(".close1")
val close2ClickStream = createButtonClickStream(".close2")
val close3ClickStream = createButtonClickStream(".close3")
def randomOffset = Math.floor(Math.random()*500)
def fetchStream(requestUrl: String) = FetchStream
.get(requestUrl)
.map(s => JSON.parse(s))
.map(r => NativeConverter[List[User]].fromNative(r))
def nextUser(users: List[User]) =
if users.isEmpty then None
else
val randomIdx = Math.floor(Math.random() * users.length).toInt
Some(users(randomIdx))
val requestStream = refreshClickStream
.map(_ => s"$githubUrl?since=$randomOffset")
val responseStream = requestStream
.flatMap(fetchStream)
.drop(1)
val clearSuggestionsStream = EventStream.merge(
EventStream.fromValue(List()),
refreshClickStream.map(_ => List())
)
def createSuggestionStream(closeClickStream: EventStream[Unit]) =
EventStream.merge(
closeClickStream
.combineWith(responseStream),
clearSuggestionsStream
).map(nextUser)
val suggestion1Stream = createSuggestionStream(close1ClickStream)
val suggestion2Stream = createSuggestionStream(close2ClickStream)
val suggestion3Stream = createSuggestionStream(close3ClickStream)
suggestion1Stream.addObserver(Observer{
user => renderSuggestion(user, ".suggestion1")
})
suggestion2Stream.addObserver(Observer {
user => renderSuggestion(user, ".suggestion2")
})
suggestion3Stream.addObserver(Observer {
user => renderSuggestion(user, ".suggestion3")
})
@main def main: Unit =
dynOwner.activate() Complete project: https://github.com/mobilemindtec/scala-examples/tree/master/fps-scalajs |
Beta Was this translation helpful? Give feedback.
-
Hello,
is there any way to simulate a "click" using a DomEventStream? I'm trying to reproduce and example in "The introduction to Reactive Programming you've been missing", and this piece is missing to finish.
I've had success calling
element.click()
directly, but I want to know if there's another way to start the flow when the app loads without someone clicking a button.This is my code:
I'm already using Laminar in some small projects, and now I'm studying AirStream to better understand how to work with Stream. I still don't have a complete understanding of reactive programming.
Thanks for the great libraries!
Beta Was this translation helpful? Give feedback.
All reactions